jar官方版本包:https://downloads.mysql.com/archives/c-j/
- mysql5驱动可以用5-8.jar,驱动包是向下兼容的
- jar5注册驱动用
com.mysql.jdbc.Driver - jar8注册驱动用
com.mysql.cj.jdbc.Driver - jar8的驱动设置数据源时,需要加上时区配置
概念
- 介绍
- jdbc是 Java DataBase Connectivity
- 是java连接数据库管理软件的技术
- 主要的工作是:发送SQL语句给数据库管理系统、获取数据库管理系统的返回的结果
- 作用
- 登录数据库,查看自己数据库的版本号

- 在官网找到与自己版本匹配的jar包:https://downloads.mysql.com/archives/c-j/

- 将jar放到当前项目的
libs文件中,导入环境
注册、创建、连接、使用、关闭
基于Prepared的CRUD
// 注册// registerDriver(new Driver());// Driver中com.mysql.cj.jdbc.Driver内部会再调用一次Driver();Class.forName("com.mysql.jdbc.Driver");// 可以使用反射直接调用内部driver()// 连接// jdbc:mysql://127.0.0.1:3306/ => jdbc:mysql:/// -> 本地库和默认端口3306可以简写// 方法一:带有ip、接口、库名、账号密码的url// DriverManager.getConnection(String url);Connection connection =DriverManager.getConnection("jdbc:mysql:///dbName?user=root&password=1234");// 方法二:带有ip、接口、库名的url 和 账号user 、 密码password// DriverManager.getConnection(String url, String user, String password);Connection connection =DriverManager.getConnection("jdbc:mysql:///dbName", "root", "1234");// 方法三:带有ip、接口、库名的url 和 有账号密码的属性的info// DriverManager.getConnection(String url, java.util.Properties info);Connection connection =DriverManager.getConnection("jdbc:mysql:///itguigu", new Properties(){{setProperty("user", "root"); setProperty("password", "1234");}});// 创建// connection是DriverManager.getConnection的返回值Statement statement = connection.createStatement();// 使用// select读取String sql = "select * from a;";ResultSet resultSet = statement.executeQuery(sql);while(resultSet.next()){int aid = resultSet.getInt(1);System.out.println(aid + " : " + resultSet.getString("id"));}// insert into写入String sql = "insert info a value (4);";int rows = statement.executeUpdate(sql);// 关闭if(selement != null) statement.close();if(root != null) root.close();
基于PreparedStatement CRUD
// 注册Class.forName("com.mysql.jdbc.Driver");// 可以使用反射直接调用内部driver()// 连接Connection connection =DriverManager.getConnection("jdbc:mysql:///dbName?user=root&password=1234");// 创建Statement statement = connection.createStatement();// 使用// select读取String sql = "select * from user where account=? and password=?";PreparedStatement preparedStatement = connection.prepareStatement(sql);preparedStatement.setObject(1,account);preparedStatement.setObject(2,password);ResultSet resultSet = preparedStatement.executeQuery();if(resultSet.next()){System.out.println("欢迎:" + resultSet.getString("name") + "登录!");}else{System.out.println("登录失败");}// insert into写入x2String sql = "insert into
