Dev_Nick

导航

jdbc操作

jdbc技术

使用java代码(程序)发送sql语句的技术。

jdbc接口核心API

jdbc相关结构在java.sql.*和javax.sql.*包下。

|- Driver接口: 表示java驱动程序接口。所有的具体的数据库厂商要来实现此接口。
  |- connect(url, properties):  连接数据库的方法。
      url: 连接数据库的URL 
           URL语法: jdbc协议:数据库子协议://主机:端口/数据库
           user: 数据库的用户名
           password: 数据库用户密码
    |- DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序
        |-registerDriver(driver)  : 注册驱动类对象
        |-Connection getConnection(url,user,password);  获取连接对象

    |- Connection接口: 表示java程序和数据库的连接对象。
         |- Statement createStatement() : 创建Statement对象
         |- PreparedStatement prepareStatement(String sql)  创建PreparedStatement对象
         |- CallableStatement prepareCall(String sql) 创建CallableStatement对象

     |- Statement接口: 用于执行静态的sql语句
         |- int executeUpdate(String sql)  : 执行静态的更新sql语句(DDL,DML)
         |- ResultSet executeQuery(String sql)  :执行的静态的查询sql语句(DQL)

     |-PreparedStatement接口:用于执行预编译sql语句
         |- int executeUpdate() : 执行预编译的更新sql语句(DDL,DML)
         |-ResultSet executeQuery()  : 执行预编译的查询sql语句(DQL)

     |-CallableStatement接口:用于执行存储过程的sql语句(call xxx)
         |-ResultSet executeQuery()  : 调用存储过程的方法


   |- ResultSet接口:用于封装查询出来的数据 |- boolean next() : 将光标移动到下一行 |-getXX() : 获取列的值

获取数据库连接的方法

常用连接数据

1 private String url = "jdbc:mysql://localhost:3306/day17";
2                         // jdbc协议:数据库子协议:主机:端口/连接的数据库   //
3 
4 private String user = "root"; //用户名
5 private String password = "root"; //密码

第一种方法:

 1 //1.创建驱动程序类对象
 2 Driver driver = new com.mysql.jdbc.Driver(); 
 3 
 4 //设置用户名和密码
 5 Properties props = new Properties();
 6 props.setProperty("user", user);
 7 props.setProperty("password", password);
 8 
 9 //2.连接数据库,返回连接对象
10 Connection conn = driver.connect(url, props);

第二种方法:使用驱动管理器类连接数据库(这里注册了两次,没必要)

Driver driver = new com.mysql.jdbc.Driver();

/1.注册驱动程序(可以注册多个驱动程序)
DriverManager.registerDriver(driver);
        
//2.连接到具体的数据库
Connection conn = DriverManager.getConnection(url, user, password);

第三种方法:使用加载驱动类来注册驱动程序,推荐使用

1 //通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
2 Class.forName("com.mysql.jdbc.Driver");
3 //2.连接到具体的数据库
4 Connection conn = DriverManager.getConnection(url, user, password);

jdbcUtils写法:

 1 import java.io.InputStream;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 import java.util.Properties;
 8 
 9 public class JdbcUtils {
10     
11     private static String url = null;
12     private static String user = null;
13     private static String password = null;
14     private static String classDriver = null;
15     static{
16         //读取系统中的配置文件
17         InputStream in = JdbcUtils.class.getResourceAsStream("/db.properties");
18         Properties property = new Properties();
19         try {
20             property.load(in);
21             url = property.getProperty("url");
22             user = property.getProperty("user");
23             password = property.getProperty("password");
24             classDriver = property.getProperty("classDriver");
25             //加载类文件        
26             Class.forName(classDriver);    
27         } catch (Exception e) {
28             e.printStackTrace();
29             throw new RuntimeException(e);
30         }
31     }
32     public static Connection getConnection(){
33         try {
34             //返回连接对象
35             return DriverManager.getConnection(url, user, password);
36         } catch (Exception e) {
37             e.printStackTrace();
38             throw new RuntimeException(e);
39         }
40     }
41     
42     public static void closeAll(Connection conn,Statement stmt,ResultSet rs){
43         try {
44             if(rs != null){
45                 rs.close();
46                 rs = null;
47             }
48             if(stmt != null){
49                 stmt.close();
50                 stmt = null;
51             }
52             if(conn != null && !conn.isClosed()){
53                 conn.close();
54                 conn = null;
55             }
56         } catch (SQLException e) {
57             e.printStackTrace();
58         }
59     }
60 }

statement执行静态SQL

1、执行DDL语句

 1 public void test1(){
 2         Statement stmt = null;
 3         Connection conn = null;
 4         try {
 5             //1.驱动注册程序
 6             Class.forName("com.mysql.jdbc.Driver");
 7             
 8             //2.获取连接对象
 9             conn = DriverManager.getConnection(url, user, password);
10             
11             //3.创建Statement
12             stmt = conn.createStatement();
13             
14             //4.准备sql
15             String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))";
16             
17             //5.发送sql语句,执行sql语句,得到返回结果
18             int count = stmt.executeUpdate(sql);
19             
20             //6.输出
21             System.out.println("影响了"+count+"行!");
22         } catch (Exception e) {
23             e.printStackTrace();
24             throw new RuntimeException(e);
25         } finally{
26             //7.关闭连接(顺序:后打开的先关闭)
27             if(stmt!=null)
28                 try {
29                     stmt.close();
30                 } catch (SQLException e) {
31                     e.printStackTrace();
32                     throw new RuntimeException(e);
33                 }
34             if(conn!=null)
35                 try {
36                     conn.close();
37                 } catch (SQLException e) {
38                     e.printStackTrace();
39                     throw new RuntimeException(e);
40                 }
41         }        
42     }
View Code

2、执行DML语句

  1         private String url = "jdbc:mysql://localhost:3306/day17";
  2     private String user = "root";
  3     private String password = "root";
  4 
  5     /**
  6      * 增加
  7      */
  8     @Test
  9     public void testInsert(){
 10         Connection conn = null;
 11         Statement stmt = null;
 12         try {
 13             //通过工具类获取连接对象
 14             conn = JdbcUtil.getConnection();
 15             
 16             //3.创建Statement对象
 17             stmt = conn.createStatement();
 18             
 19             //4.sql语句
 20             String sql = "INSERT INTO student(NAME,gender) VALUES('李四','女')";
 21             
 22             //5.执行sql
 23             int count = stmt.executeUpdate(sql);
 24             
 25             System.out.println("影响了"+count+"行");
 26             
 27         } catch (Exception e) {
 28             e.printStackTrace();
 29             throw new RuntimeException(e);
 30         } finally{
 31             //关闭资源
 32             JdbcUtil.close(conn, stmt);
 33         }
 34     }
 35     
 36     /**
 37      * 修改
 38      */
 39     @Test
 40     public void testUpdate(){
 41         Connection conn = null;
 42         Statement stmt = null;
 43         //模拟用户输入
 44         String name = "陈六";
 45         int id = 3;
 46         try {
 47             /*//1.注册驱动
 48             Class.forName("com.mysql.jdbc.Driver");
 49             
 50             //2.获取连接对象
 51             conn = DriverManager.getConnection(url, user, password);*/
 52             //通过工具类获取连接对象
 53             conn = JdbcUtil.getConnection();
 54             
 55             //3.创建Statement对象
 56             stmt = conn.createStatement();
 57             
 58             //4.sql语句
 59             String sql = "UPDATE student SET NAME='"+name+"' WHERE id="+id+"";
 60             
 61             System.out.println(sql);
 62             
 63             //5.执行sql
 64             int count = stmt.executeUpdate(sql);
 65             
 66             System.out.println("影响了"+count+"行");
 67             
 68         } catch (Exception e) {
 69             e.printStackTrace();
 70             throw new RuntimeException(e);
 71         } finally{
 72             //关闭资源
 73             JdbcUtil.close(conn, stmt);
 74         }
 75     }
 76     
 77     /**
 78      * 删除
 79      */
 80     @Test
 81     public void testDelete(){
 82         Connection conn = null;
 83         Statement stmt = null;
 84         //模拟用户输入
 85         int id = 3;
 86         try {
 87             /*//1.注册驱动
 88             Class.forName("com.mysql.jdbc.Driver");
 89             
 90             //2.获取连接对象
 91             conn = DriverManager.getConnection(url, user, password);*/
 92             //通过工具类获取连接对象
 93             conn = JdbcUtil.getConnection();
 94             
 95             //3.创建Statement对象
 96             stmt = conn.createStatement();
 97             
 98             //4.sql语句
 99             String sql = "DELETE FROM student WHERE id="+id+"";
100             
101             System.out.println(sql);
102             
103             //5.执行sql
104             int count = stmt.executeUpdate(sql);
105             
106             System.out.println("影响了"+count+"行");
107             
108         } catch (Exception e) {
109             e.printStackTrace();
110             throw new RuntimeException(e);
111         } finally{
112             //关闭资源
113             JdbcUtil.close(conn, stmt);
114         }
115     }    
View Code

3、执行DQL语句

 1 public void test1(){
 2         Connection conn = null;
 3         Statement stmt = null;
 4         try{
 5             //获取连接
 6             conn = JdbcUtil.getConnection();
 7             //创建Statement
 8             stmt = conn.createStatement();
 9             //准备sql
10             String sql = "SELECT * FROM student";
11             //执行sql
12             ResultSet rs = stmt.executeQuery(sql);
13             //遍历结果
14             while(rs.next()){
15                 int id = rs.getInt("id");
16                 String name = rs.getString("name");
17                 String gender = rs.getString("gender");
18                 System.out.println(id+","+name+","+gender);
19             }
20             
21         }catch(Exception e){
22             e.printStackTrace();
23             throw new RuntimeException(e);
24         }finally{
25             JdbcUtil.close(conn, stmt);
26         }
27     }
View Code

PreparedStatement执行动态SQL,可以有效防止sql注入

 1 public void testByPreparedStatement(){
 2         Connection conn = null;
 3         PreparedStatement stmt = null;
 4         ResultSet rs = null;
 5         try {
 6             //获取连接
 7             conn = JdbcUtil.getConnection();
 8             
 9             String sql = "SELECT * FROM users WHERE NAME=? AND PASSWORD=?";
10             
11             //预编译
12             stmt = conn.prepareStatement(sql);
13             
14             //设置参数
15             stmt.setString(1, name);
16             stmt.setString(2, password);
17             
18             //执行sql
19             rs = stmt.executeQuery();
20             
21             if(rs.next()){
22                 //登录成功
23                 System.out.println("登录成功");
24             }else{
25                 System.out.println("登录失败");
26             }
27             
28         } catch (Exception e) {
29             e.printStackTrace();
30             throw new RuntimeException(e);
31         } finally {
32             JdbcUtil.close(conn, stmt ,rs);
33         }
34         
35     }
View Code

 元数据

元数据分为三种:

1、数据库元数据(连接元数据)、参数元数据、结果集元数据。

数据库元数据

public void testDB() throws Exception {
        // 获取连接
        Connection conn = JdbcUtil.getConnection();
        // 获取数据库元数据
        DatabaseMetaData metaData = conn.getMetaData();
        System.out.println(metaData.getUserName());
        System.out.println(metaData.getURL());
        System.out.println(metaData.getDatabaseProductName());
    }

参数元数据

public void testParams() throws Exception {
        // 获取连接
        Connection conn = JdbcUtil.getConnection();
        // SQL
        String sql = "select * from dept where deptid=? and deptName=?";
        // Object[] values = {"tom","888"};
        
        PreparedStatement pstmt = conn.prepareStatement(sql);
        // 参数元数据
        ParameterMetaData p_metaDate = pstmt.getParameterMetaData();
        // 获取参数的个数
        int count = p_metaDate.getParameterCount();
        
        
        // 测试
        System.out.println(count);
    }

结果集元数据

public void testRs() throws Exception {
        String sql = "select * from dept ";
        
        // 获取连接
        Connection conn = JdbcUtil.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        // 得到结果集元数据(目标:通过结果集元数据,得到列的名称)
        ResultSetMetaData rs_metaData = rs.getMetaData();
        
        // 迭代每一行结果
        while (rs.next()) {
            // 1. 获取列的个数
            int count = rs_metaData.getColumnCount();
            // 2. 遍历,获取每一列的列的名称
            for (int i=0; i<count; i++) {
                // 得到列的名称
                String columnName = rs_metaData.getColumnName(i + 1);
                // 获取每一行的每一列的值
                Object columnValue = rs.getObject(columnName);
                // 测试
                System.out.print(columnName + "=" + columnValue + ",");
            }
            System.out.println();
        }
        
    }

 

posted on 2017-05-05 16:50  Dev_Nick  阅读(248)  评论(0编辑  收藏  举报