JDBC基础
使用JDBC的开发步骤:
1. 注册驱动com.mysql.jdbc.Driver(加载到内存中) DriverManager
2. 创建连接Connection
3. 发送SQL语句给数据库,Statement
4. 返回查询的结果 ResultSet5. 关闭连接对象
一. 什么是JDBC(JavaDataBase connectivity):Java访问数据库的连接技术
1. 组成: 由一组接口组成,几乎用到的都是接口
2 .JDBC用到的包:
1) java.sql: Java访问数据库的基础包
2) javax.sql: java访问数据库的扩展,入使用一些高级特性
3) 驱动: mysql的驱动包jar
mysql-connector-java-xxxx-bin.jar
二. 使用JDBC连接数据库的四个参数
1) 用户名
2) 密码
3) 数据库连接字符串 URL格式: 协议名:子协议名://服务名:端口号/数据库名[?参数名=参数值&参数名=参数值]
4) 指定驱动名 com.mysql.jdbc.Driver
三. JDBC的核心API
1. API概述
Driver: 接口,所有产商的驱动都必须要实现这个接口
DriverManager: 驱动管理器类, 组注册驱动,管理驱动(可以不再需要使用
Class.forName()显式地加载 JDBC 驱动程序)Connection: 接口,代表数据库访问的连接对象
Statement: 接口, 代表发送给数据库服务器的SQL语句
ResultSet: 接口, 代表数据库返回的查询结果
2. DriverManager类
1) 作用:
1) 注册驱动 DriverManager.registerDriver(new Driver())
2) 管理各种数据库的驱动
2) 方法:(得到连接对象)
public static Connection getConnection(String url, String user, String password)
url: 数据库连接字符串
user: 用户名
password: 密码
mysql中Connection接口的实现类是:JDBC4Connection
public static Connection getConnection(String url, Properties info)
url: 数据库连接字符串
info: 把用户名,密码等信息保存在属性集中
3. Connection接口:(连接对象)
Statement createStatement() 创建一个语句对象,没有提供SQL语句。
PreparedStatement prepareStatement(String sql) 提供了SQL语句
4. Statement接口:(语句对象,代表一条发送给数据库服务器的SQL语句)(下面有preparedStatement接口,具有预编译功能,执行效率更高,推荐使用)
int executeUpdate(String sql) :用于增删改的操作
sql: 要发送的SQL语句
返回影响的行数
ResultSet executeQuery(String sql) : 用于查询的操作
sql: 发送的SQL语句
返回查询的结果集
关闭资源的顺序: ResultSet --> Statement --> Connection
1 public void testInsert() throws Exception { 2 // 1. 注册驱动 3 Class.forName("com.mysql.jdbc.Driver"); 4 // 2. 得到连接 5 Connection conn = DriverManager.getConnection("jdbc:mysql:///day24", "root", "root"); 6 // 3 创建语句对象 7 Statement stmt = conn.createStatement(); 8 // 4. 执行DML语句 9 int row = stmt.executeUpdate("insert into student (name,gender,birthday) values ('孙悟空','男','1997-11-23')"); 10 System.out.println("添加" + row + "条记录"); 11 // 5. 关闭资源 12 stmt.close(); 13 conn.close(); 14 }
四. 执行DQL查询操作
1. ResultSet接口: 代表查询返回的所有数据库的记录
1) 接口中的方法:
boolean next() :
1) 指针向下移动一行
2) 返回一个boolean类型,如果指针指向最后一条记录的后面,返回false
getXXX()两种参数:
1) 通过列名:getInt("id") getString("gender")
2) 通过列号:getInt(1) getString(3)
2) 注意:(没有next直接取值或是已经到达结果集的尾部)
3.1). 第一行之前: java.sql.SQLException: Before start of result set
3.2). 最后一行之后: java.sql.SQLException: After end of result set
3.3). 关闭顺序: 先关ResultSet,再关Statement,再关Connection
2. 常用数据类型转换表
SQL类型 Jdbc对应方法 返回类型
BIT(1) bit(n) getBoolean getBytes() Boolean byte[]
TINYINT getByte() Byte
SMALLINT getShort() Short
Int getInt() Int
BIGINT getLong() Long
CHAR,VARCHAR getString() String
Text(clob) getClob Clob
Blob getBlob() Blob
DATE getDate() java.sql.Date
TIME getTime() java.sql.Time
TIMESTAMP getTimestamp() java.sql.Timestamp
1 public void testQuery() throws Exception { 2 //1. 注册驱动 3 Class.forName("com.mysql.jdbc.Driver"); 4 //2. 得到连接 5 Connection conn = DriverManager.getConnection("jdbc:mysql:///day24","root","root"); 6 //3. 创建语句对象 7 Statement stmt = conn.createStatement(); 8 //4. 执行SQL语句,返回结果集 9 ResultSet rs = stmt.executeQuery("select * from student"); 10 //if当查询的结果只有一行的时候 11 while(rs.next()) { 12 //通过列名 13 // System.out.println("编号:" + rs.getInt("id")); 14 // System.out.println("姓名:" + rs.getString("name")); 15 // System.out.println("性别:" + rs.getString("gender")); 16 // System.out.println("生日:" + rs.getDate("birthday")); 17 //通过列号 18 System.out.println("编号:" + rs.getInt(1)); 19 System.out.println("姓名:" + rs.getString(2)); 20 System.out.println("性别:" + rs.getString(3)); 21 System.out.println("生日:" + rs.getDate(4)); 22 System.out.println("----------------------"); 23 } 24 //5.释放资源 25 rs.close(); 26 stmt.close(); 27 conn.close(); 28 }
五. PreparedStatement接口: (Prepared意思: 预先准备好的)
1. 概述:
1) 是Statement的子接口
public interface PreparedStatement extends Statement
2. Statement和PreparedStatement
1).区别:
a) PreparedStatement有预编译的功能,执行效率上更高。所以在创建对象的时候就提供了SQL语句。
在执行SQL语句的时候,不再需要提供SQL语句
b) 在执行的时候有缓存的功能,在执行大量SQL语句的时候效率会更高。
c) 安全性: 没有SQL注入的风险,没有字符的拼接。
2). 接口中的方法:
int executeUpdate() 增删改的操作
ResultSet executeQuery() 查询的操作
3. 使用PreparedStatement的步骤:
1) 创建 PreparedStatement prepareStatement(String sql):
sql: select * from user where name=? and password=?
2) SQL语句中的所有参数使用?,占位符来占位
3) 在执行前,将?全部换成真实的参数
setXxx(占位符的位置, 真实的值) Xxx 代表数据类型
如: setString(1, "张三");
在实际的应用中,一般不直接返回结果集给用户。返回一个已经封装好的集合给用户
1 /** 2 * 封装成List<Student>返回 3 */ 4 public static List<Student> findAllStudents() { 5 //创建一个集合 6 List<Student> students = new ArrayList<>(); 7 Connection conn = null; 8 PreparedStatement ps = null; 9 ResultSet rs = null; 10 try { 11 conn = JdbcUtil.getConnection(); 12 ps = conn.prepareStatement("select * from student"); 13 rs = ps.executeQuery(); 14 15 //封装数据 16 while(rs.next()) { 17 Student student = new Student(); 18 student.setId(rs.getInt("id")); 19 student.setName(rs.getString("name")); 20 student.setGender(rs.getString("gender")); 21 student.setBirthday(rs.getDate("birthday")); 22 //添加到集合中 23 students.add(student); 24 } 25 } catch (SQLException e) { 26 e.printStackTrace(); 27 } finally { 28 JdbcUtil.close(conn, ps, rs); 29 } 30 return students; 31 }
1 /** 2 * 工具类 3 */ 4 public class JdbcUtil { 5 6 /** 7 * 可以把几个字符串定义成常量 8 */ 9 private static final String USER = "root"; //用户名 10 private static final String PASSWORD = "root"; 11 private static final String URL = "jdbc:mysql://localhost:3306/day24"; 12 private static final String DRIVER = "com.mysql.jdbc.Driver"; 13 14 /** 15 * 在静态代码块中注册驱动,只需注册一次即可。 16 */ 17 static { 18 try { 19 Class.forName(DRIVER); 20 } catch (ClassNotFoundException e) { 21 e.printStackTrace(); 22 } 23 } 24 25 /** 26 * 得到数据库的连接 27 */ 28 public static Connection getConnection() { 29 try { 30 return DriverManager.getConnection(URL, USER, PASSWORD); 31 } catch (SQLException e) { 32 e.printStackTrace(); 33 throw new RuntimeException(e); 34 } 35 } 36 37 /** 38 * 关闭所有打开的资源 39 */ 40 public static void close(Connection conn,Statement stmt,ResultSet rs) { 41 if (rs!=null) { 42 try { 43 rs.close(); 44 } catch (SQLException e) { 45 e.printStackTrace(); 46 } 47 } 48 49 if (stmt!=null) { 50 try { 51 stmt.close(); 52 } catch (SQLException e) { 53 e.printStackTrace(); 54 } 55 } 56 57 if (conn!=null) { 58 try { 59 conn.close(); 60 } catch (SQLException e) { 61 e.printStackTrace(); 62 } 63 } 64 } 65 66 /** 67 * 关闭没有结果集的资源 68 * @param conn 69 * @param stmt 70 */ 71 public static void close(Connection conn,Statement stmt) { 72 close(conn, stmt, null); 73 } 74 }

浙公网安备 33010602011771号