第一步:
通过反射加载驱动:
Class.forName("com.mysql.cj.jdbc.Driver");这时需要处理ClassNotFoundException
加载mysql数据库驱动:(向下兼容)
mysql5:com.mysql.jdbc.Drivermysql8:com.mysql.cj.jdbc.Driver第二步:
设置连接的URL信息:
useUnicode=true:可以显示中文characterEncoding=utf8:设置编码为utf-8useSSL=true:使用安全连接serverTimezone=Asia/Shanghai:设置mysql的时区,mysql8默认时区是美国第三步:
创建连接对象:
Connection conn = DriverManager.getConnection(url, username, password);这时有可能会产生SQLException,需要抛出或捕获
第四步:
创建执行SQL语句的对象(Statement/preparedStatement)
Statement:发送完整的SQL语句到数据库,不是直接执行,而是由数据库先编译,再运行
preparedStatement:可以使用占位符,是预编译的,他发送的是可以直接运行的SQL语句到数据库,数据库不需要编译,批处理比Statement效率高
preparedStatement:
String sql = "insert into user values (?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql);Statement:
String sql = "insert into `user` values (8,'mc',20,'442261507@qq.com')"; Statement s = conn.createStatement();第五步:
preparedStatement:
设置预编译的参数:
ps.setInt(1,6); ps.setString(2,"马"); ps.setInt(3,21); ps.setString(4,"442261578@qq.com"); int update = ps.executeUpdate(sql); System.out.println(update); //插入成功,返回 1这时需要注意传入的数据类型,第一个参数的意思是插入的是第几个占位符(从1开始数),第二个参数就是要插入的数据
Statement:
int update = s.executeUpdate(sql); System.out.println(update); //插入成功,返回 1第六步:
依次关闭开启的资源
ps.close(); conn.close();完整的示例如下:
//加载数据库驱动 try { Class.forName("com.mysql.cj.jdbc.Driver"); //设置连接URL String url = "jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai"; String username = "root"; String password = "mc123"; //创建连接 try { Connection conn = DriverManager.getConnection(url, username, password); //创建执行SQL语句的对象(statement/preparedStatement) String sql = "insert into user values (?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); //设置参数(注意数据类型) ps.setInt(1,6); ps.setString(2,"马聪"); ps.setInt(3,21); ps.setString(4,"442261507@qq.com"); //执行插入操作 int update = ps.executeUpdate(); System.out.println(update); //插入成功,返回 1 //关闭开启的资源 ps.close(); conn.close(); } catch (SQLException e) { System.out.println("创建连接失败!"); e.printStackTrace(); } } catch (ClassNotFoundException e) { System.out.println("加载不到数据库驱动!"); e.printStackTrace(); }