1、对JDBC的理解
jdbc是sun公司规定的一套java程序访问数据库的接口。数据库厂商完成对接口的实现,也就是常说的驱动程序。
程序员(接口调用)<----->jdbc(接口定义)<---->数据库厂商(接口实现)
2、JDBC的写法
我用的mysql数据库
版本号:5.7.38
驱动包:5.1.49
驱动程序下载地址:MySQL :: Download Connector/J
(1)注册驱动
Class.forName("com.mysql.jdbc.Driver");
com.mysql.jdbc.Driver为mysql-connector-java 5的驱动名称。
com.mysql.cj.jdbc.Driver为mysql-connector-java 6的驱动名称。
JDBC4.0后自动加载注册驱动,此步骤可以省略。
(2)获取数据库连接对象
String url = "jdbc:mysql://127.0.0.1:3306/db?useSSL=false&&characterEncoding=utf-8"; //此处可以省略为jdbc:mysql:///db?useSSL=false&&characterEncoding=utf-8 //characterEncoding=utf-8设置字符编码,不然中文会出现乱码 String user = "root";//用户名 String password = "123456";//密码 Connection conn = DriverManager.getConnection(url, user, password);//固定格式
url,user,password一般放入配置文件内,配置文件加载方式可自行百度。
(3)获取sql执行对象
String stmtSql = "select * from table where id = 1"; Statement stmt = conn.createStatement();
需注意的是Statement存在sql注入问题(字符串拼接)
防止sql注入可以使用PrearedStatement,PrearedSatement是预编译的
String psSql = "select * from table where id = ?" ; PreparedStatement ps = ps = conn.prepareStatement(psSql); ps.setXxx(index,xxx);//设置占位符(?)的参数 //Xxx代表String、Int等,index从1开始,xxx需传入的参数
(4)执行sql
Statement
ResultSet rs = stmt.executeQuery(stmtSql);//查询语句,返回查询结果集 int count = stmt.executeUpdate(sql);//增删改语句,返回结果代表影响了几行
PreparedStatement
ResultSet rs = ps.executeQuery();//查询,返回查询结果集 int count = ps.executeUpdate();//增删改,返回影响几行
(5)处理查询结果集(查询)
ResultSet rs简单介绍:
假设查询结果集为:
rs有一个对行操作的光标,一开始这个光标指向id这一行。
id name age birthday 1 “张三” 23 1999-2-3 2 “李四” 25 2002-3-4
rs.next()方法,验证当前光标下一行是否有数据,若有数据光标下移一行并返回true, 无 数据则返回false获取数据方法:
rs.getString(index);//返货光标所在行的数据,index为列数,从1开始,例如id为1 rs.getString("key");//key为列的名称 //其他方法还有,rs.getInt(),rs.getDate()等,
输出上表所有数据代码为
//(1) while(rs.next()){ int id = rs.getInt(1); String name = rs.getString(2); int age = rs.getInt(3); Date birthday = rs.getDate(4); System.out.println("id = " + id +"," + " name = " + name + "," + " age = " + age + "birthday = " + birthday ); } //(2) while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("birthday"); int age = rs.getInt("age"); Date birthday = rs.getDate("birthday"); System.out.println("id = " + id +"," + " name = " + name + "," + " age = " + age + "birthday = " + birthday ); }
(6)释放资源
//从小到大原则 rs.close(); stmt.close()//或ps.close(); conn.close();
补充
jdbc默认自动提交事务,若需手动提交事务,可在(3)后面添加下面代码
//关闭自动提交事务 conn.setAutoCommit(false);
在最后记得提交事务
//提交事务 conn.commit();
下面附上完整代码
Statement+自动提交事务
package com.study.jdbc; import java.sql.*; /** * @author 22805 * 不加载配置文件 */ public class test01 { public static void main(String[] args) throws ClassNotFoundException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //注册驱动; Class.forName("com.mysql.jdbc.Driver"); //获取mysql链接; String url = "jdbc:mysql://127.0.0.1:3306/stock"; String user = "root"; String password = "xxxxx"; conn = DriverManager.getConnection(url, user, password); //获取执行sql的对象 stmt = conn.createStatement(); //执行sql String queryString = "select id,code,date from daily"; //处理结果集 rs = stmt.executeQuery(queryString); while(rs.next()){ int id = rs.getInt("id"); String code = rs.getString("code"); String date = rs.getString(3); System.out.println("id="+id+";code="+code+";date="+date); } } catch (SQLException e) { e.printStackTrace(); }finally { //释放资源 if(conn!=null){ try{ conn.close(); }catch (SQLException e){ e.printStackTrace(); } } if(stmt!=null){ try{ stmt.close(); }catch (SQLException e){ e.printStackTrace(); } } if(rs!=null){ try{ rs.close(); }catch (SQLException e){ e.printStackTrace(); } } } } }
PreparedStatement+自动提交事务package com.study.jdbc; import java.sql.*; import java.util.ResourceBundle; /** * @author 22805 */ public class test03 { public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //注册驱动 Class.forName(className); //获取数据库连接 String url = "jdbc:mysql://127.0.0.1:3306/stock"; String user = "root"; String password = "xxxxx"; conn = DriverManager.getConnection(url, user, password); //开启事务 conn.setAutoCommit(false); //获取预编译操作sql数据库对象 String sql = "select code,date from daily where id = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, 1); //执行sql rs = ps.executeQuery(); //处理查询子集 if (rs.next()) { String code = rs.getString("code"); int date = rs.getInt(2); System.out.println("code:" + code + ";date:" + date); } String queryString = "update daily set code = ? ,date = ? where id = ?"; ps = conn.prepareStatement(queryString); ps.setInt(1, 1); ps.setInt(2, 2);//我数据库date为int类型,不要误解 ps.setInt(3, 1); int count = ps.executeUpdate(); System.out.println(count); conn.commit(); } catch (Exception e) { //若执行过程中出现,数据回滚,保证数据安全 if (conn != null) { try { conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } } e.printStackTrace(); } finally { //释放资源 if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }