测试环境:
- 编译器:idea64-2023 .
- jdk17.
- mysql8.0.
- mysql-connector-java-8.0.22.jar
简单来说六个步骤:
1、注册驱动(加载驱动)
Class.forName("com.mysql.cj.jdbc.Driver"); // 注册驱动
2、创建连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT","root","20010920");
getConnection()方法中的参数为:“jdbc:数据库类型://ipv4地址或者本地localhost:数据库端口号/数据库名称?[字符编码]&时区”
3、编写需要的sql语句
String sql = "update teacher set tname = ? ,sal = ? ,hirdate = ? where tid = ?";
4、创建执行对象
PreparedStatement pstmt = connection.prepareStatement(sql);
4、设置值
//设置值
// 第一个参数是索引,代表第一个?,第二个是值
pstmt.setObject(1,"奥塔慢");
pstmt.setObject(2,23);
pstmt.setObject(3,"1999-1-1");
pstmt.setObject(4,2);
5、执行sql
pstmt.executeUpdate();
6、关闭连接
pstmt.close();
connection.close();