1.注册驱动
Driver driver = new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);
2.获取链接
String url = "jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT ";
String user = "******";
String password = "*********";
conn = DriverManager.getConnection(url, user, password);
System.out.println("数据库连接对象 = " + conn);
3.获取数据库操作对象
stmt = conn.createStatement();
4.执行SQL语句
String sql = "insert into student(id,name,age,sex,address,math,english) values(11,'uu',15,'女','上海',100,100)";
int count = stmt.executeUpdate(sql);
System.out.println(count == 1 ? "保存成功" : "保存失败");
5.处理查询结果集
6.释放资源
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}