1、加载驱动Class.forName("");
Class.forName("com.mysql.jdbc.Driver");
2、获得连接对象Connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8", "***", "***");
//前面写上地址,?前面的java是数据库名称,根据实际情况改变,最后两个引号是用户名和密码,根据实际情况改变
3、写sql语句
String sql = "SELECT id,name,age,gender FROM student";
//随便写的
4、创建Statement(一艘船)
statement = connection.createStatement();
5、执行sql语句
// (1) 更新类(更改了表里面数据):delete/update/insert executeUpdate()
// 返回值:int,表示你影响的行数
// (2)查询(没有改变表里面数据): select executeQuery()
// 返回值:结果集ResultSet
//PreparedStatement 使用预编译的sql
6、关闭连接
//先打开后关闭
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
JDBC工具类的创建
static {
try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
加载驱动以静态代码块的方式,避免了每次连接都需要加载一次
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/homework?useUnicode=true&characterEncoding=UTF-8”, “root”, “342516”);
return connection;
}
public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){
//先打开后关闭
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}