- 加载数据库驱动到java虚拟机 (Class.forName)
- 建立数据库连接(url)
- 创建数据库的操作对象 (getConnection)
- 定义SQL语句
- 执行数据库操作 (execteQuery)
- 获取数据集(Resultset)
- 关闭数据库对象(Resultset,Statement,Connection)
代码实例:JdbcUtil.java
package dbc;
import java.sql.*;
import java.util.Properties;
public final class JdbcUtil {
private static String driver ="" ;
private static String url = "" ;
private static String user = "" ;
private static String password = "" ;
private static Properties pr=new Properties();
private JdbcUtil(){}
static {
try {pr.load(JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties"));
driver=pr.getProperty("driver");
url=pr.getProperty("url");
user=pr.getProperty("username");
password=pr.getProperty("password");
Class.forName(driver);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void free(ResultSet rs, Statement st, Connection conn) {
try { if (rs != null) rs.close();
} catch (SQLException e) {e.printStackTrace();
} finally {
try { if (st != null) st.close();
} catch (SQLException e) {e.printStackTrace();
} finally {
if (conn != null)
try { conn.close();
} catch (SQLException e) {e.printStackTrace();}
}
}
}
}
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/Car_Sale?useUnicode=true&characterEncoding=utf-8
username=root
password=root