JDBC,全称 Java Database Connectivity
在Java中用来规范如何访问关系型数据库,由各大数据库厂商去实现它
下载MySQL的JDBC实现(jar,驱动包)
下载地址 选择 MySQL Product Archives
版本选择 最新的 (我项目中是 5.1.49)
platform independent (平台独立)
JDBC使用步骤
1.将Driver(驱动程序)注册到DriverManager(驱动程序管理者)
2.利用DriverManager创建Connection(数据库连接)
3.利用Connetion创建 Statement(语句)
4.利用Statement执行Sql语句
5.关闭资源(关闭Statement语句、Connetion连结等)
注册驱动
DriverManager.registerDriver(new Driver());
或者
Class.forName("com.mysql.jdbc.Driver"); //主动加载类库 可以省略
细节:
6.x之前驱动
com.mysql.jdbc.Driver
6.x之后驱动
com.mysql.cj.jdbc.Driver
项目中如果只导入一个mysql驱动包不需要注册也可以
创建 Connection
Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
mysql的url格式
jdbc:mysql://ip地址:端口号/数据库名 默认端口 3306 加上时区
private static final String URL = "jdbc:mysql://localhost:3306/xmg?serverTimezone=UTC";
private static final String USERNAME = "root";
private static final String PASSWORD = "111111";
创建 Statement
Statement statement = connection.createStatement();
执行sql语句 并且关闭
Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery("select *from user;");
boolean execute = statement.execute("select *from user");
// 执行语句 并且关闭
System.out.println(set);
System.out.println(execute);
set.close();
statement.close();
connection.close();
Statement、PreparedStatement
executeQuery
执行DQL语句 返回ResultSet
executeUpdate
执行DML、DDL语句
如果DML语句,返回值代表影响的记录数量;如果数据库没有任何返回值,通常返回0
ResultSet
next() 游标,如果指向这行有数据,就返回true,否则false
xx getxx(int columnIndex)、xx getxx(String columnLabel)
获取当前行 某一行的数据
columnIndex数值从1开始
细节
- 如果数据库field字段是stirng 你用int接受如果字符串是123这样的可以转的 但是如果是
你好用int接收则失败 - 如果你sql 是select * 则可以取出所有数据 如果是 select username xxx 如果你的columnIndex、columnLabel 都错误了 columnLabel是password 那么就取不出来 会抛异常
PreparedStatement 优势
- 可以防止sql注入
- 执行速度比Statement快
- 支持批量处理
如果? 用于字段 拼接出来 带双引号 这样sql 错误 可以用于values where 后面值
PreparedStatement statement = connection.prepareStatement("select username,id,password from user where username = ? and password = ?;");
statement.setString(1,"mosi");
statement.setString(2,"9999");