JDBC的应用

时间:2023-03-08 17:40:56
JDBC的应用
JDBC的开发步骤:
1.  引入JDBC驱动架包
2.  程序中引入JDBC驱动类    
3.  创建java与数据库的连接
4.  跟数据库交互:发送sql语句,接收数据库对sql语句的执行结果
5.  解析执行结果
先写入执行代码,快捷键shift+alt+z,写出try与catch代码块
使用到的相关接口;
Connection接口
DriverManager接口
Statement接口
ResultSet接口
程序引入驱动类:
 Class.forName("com.mysql.jdbc.Driver");
创建java与数据库的连接:
Connection conn = DriverManager getConnection(url,username,password);
--------------------------------------------------------------------
原理:
public static Connection getConnection(String url,
                                       String user,
                                       String password)
                                throws SQLException
试图建立到给定数据库 URL 的连接。DriverManager 试图从已注册的 JDBC 驱动程序集中选择一个适当的驱动程序。
参数:
url - jdbc:subprotocol:subname 形式的数据库 url
user - 数据库用户,连接是为该用户建立的
password - 用户的密码
返回:
到 URL 的连接
抛出:
SQLException - 如果发生数据库访问错误
Connection接口不能够自己new对象,DriverManager中有getConnection可以创建对象
----------------------------------------------------------------------------------------------------------------------------------------
 跟数据库交互:发送sql语句,接收数据库对sql语句的执行结果:
Statement 接口,用于执行静态 SQL 语句并返回它所生成结果的对象。
Statement stmt=conn.createStatement();                          //创建Statement对象
            String sql="select*from tb_book";
ResultSet rs=stmt.executeQuery(sql);             //Statement执行静态sql语句并返回结果,结果使用ResultSet类型来接收
API:

createStatement

Statement createStatement()
                          throws SQLException
创建一个 Statement 对象来将 SQL 语句发送到数据库。不带参数的 SQL 语句通常使用 Statement 对象执行。如果多次执行相同的 SQL 语句,使用 PreparedStatement 对象可能更有效。

使用返回的 Statement 对象创建的结果集在默认情况下类型为 TYPE_FORWARD_ONLY,并带有 CONCUR_READ_ONLY 并发级别。已创建结果集的可保存性可调用 getHoldability() 确定。

返回:
一个新的默认 Statement 对象
抛出:
SQLException
- 如果发生数据库访问错误,或者在关闭的连接上调用此方法

----------------------------------------------------------------------------------------------------------------------------------------

ResultSet接口:

1.表示数据库结果集的数据表,通常通过执行查询数据库的语句生成。

2.ResultSet 对象具有指向其当前数据行的光标。最初,光标被置于第一行之前。next 方法将光标移动到下一行;因为该方法在 ResultSet 对象没有下一行时返回 false,所以可以在 while 循环中使用它来迭代结果集。

查找数据表代码:
try {
            Class.forName("com.mysql.jdbc.Driver");
            String url= "jdbc:mysql://localhost:3306/test_1";
            String username = "root";
            String password = "Boyce";
            Connection conn = DriverManager.getConnection(url, username, password);
            String sql="select*from tb_books where name=? and author=?";    
//            Statement statement= conn.createStatement(); 
            PreparedStatement statement =conn.prepareStatement(sql);//通过Statement与数据库交互
            statement.setInt(1, 33);                    //1代表sql语句中从左边数第一个问号,22代表sql语句中的name的值
            statement.setString(2,"33");
            //两个参数时,必须在同一行,因为要指出同一个数值
            ResultSet rs = statement.executeQuery();    //执行静态SQL语句,并返回结果
            //解析resultSet结果集,所接收的返回结果
            //ResultSet 对象具有指向其当前数据行的光标。最初,光标被置于第一行之前。next 方法将光标移动到下一行;
            //因为该方法在 ResultSet 对象没有下一行时返回 false,所以可以在 while 循环中使用它来迭代结果集。 
            while(rs.next())
            {                
//                System.out.println(rs.getString(1));                      //括号中的数值代表某一类属性值,也可以说是一列数值
                System.out.println(rs.getString("author"));
                System.out.println(rs.getString(2));
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
----------------------------------------------------------------------------------------------------------------------------------------
JDBC插入数据表记录
Class.forName("com.mysql.jdbc.Driver");
            String url= "jdbc:mysql://localhost:3306/test_1";
            String username = "root";
            String password = "Boyce";
            Connection conn = DriverManager.getConnection(url, username, password);
            String sql ="insert into tb_books values(?,?,?,?)";
            PreparedStatement statement =conn.prepareStatement(sql);//通过Statement与数据库交互    多个参数   
            statement.setString(1,"cyuyan");
            statement.setDouble(2, 100);
            statement.setString(3, "20");
            statement.setString(4, "lijianwei");
            int rs = statement.executeUpdate();                 //是executeUpdate()而不是executeQuery()
            if(rs!=0){                                                                //返回整数,如果re==1则插入成功,返回值为0则插入失败
                System.out.println("插入成功");
            }else
            {
                System.out.println("插入时报");
            }
----------------------------------------------------------------------------------------------------------------------------------------
JDBC更新数据表记录
 
Class.forName("com.mysql.jdbc.Driver");
            String url= "jdbc:mysql://localhost:3306/test_1";
            String username = "root";
            String password = "Boyce";
            Connection conn = DriverManager.getConnection(url, username, password);
            String sql = "update tb_books set name=?where author='lijianwei'";   //问号设置为math  根据author为lijianwei去查找,若author是String类型则注意要加上单引号
            PreparedStatement statement =conn.prepareStatement(sql);//通过Statement与数据库交互    多个参数
            statement.setString(1,"cyuyan");
            int rs = statement.executeUpdate();
            if(rs!=0){
                System.out.println("插入成功");
            }else
            {
                System.out.println("插入时报");
            }
  ----------------------------------------------------------------------------------------------------------------------------------------

JDBC批量插入:

public class JDBCTest1 {
    private  static String url= "jdbc:mysql://localhost:3306/test_1";
    private  static String username = "root";
    private  static String password = "Boyce";
    /**
     * 载入驱动类
     */
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 获取连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getconection() throws SQLException{
                return DriverManager.getConnection(url, username, password);
        }
    //释放资源
    public static void free(Connection conn,Statement statement,ResultSet rs){
        try {
            if(rs!=null)  
            rs.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{                                            //不管rs是否关闭成功,都会执行finally块
            try {
                if(statement!=null)
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    if(conn!=null)
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
public class JDBCTest2 {
    /**
     * 查询表记录
     * @param sql
     * @throws SQLException 
     */
    public void queryAll(String sql) throws SQLException{
        Connection conn = JDBCTest1.getconection();            //不需要new对象调用,JAVA中同一个包内的方法可通过类名直接调用
        Statement statement = conn.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        //解析rs内容
        while(rs.next())
            {                
                System.out.println(rs.getString(1));                      //括号中的数值代表某一类属性值,也可以说是一列数值
                System.out.println(rs.getString("author"));
                System.out.println(rs.getString(2));                
            }
        JDBCTest1.free(conn, statement, rs); 
    }
    public void isertBatch() throws SQLException{
        Connection conn = JDBCTest1.getconection();
        conn.setAutoCommit(false);                          //不自动提交,因为如果有一个失败时,可以整体回滚
        String sql ="insert into tb_books values(?,?,?,?)";
        PreparedStatement statement = conn.prepareStatement(sql);
        for(int i=1;i<5;i++)
        {
            statement.setString(1, "boyce"+i);
            statement.setDouble(2, 100+i);
            statement.setString(3, "i"+i);
            statement.setString(4, "boyce");
            statement.addBatch();   
        }
        statement.executeBatch();                         //同一提交给数据库
        conn.commit();                                    //注意提交事务
        JDBCTest1.free(conn, statement, null);
        System.out.println("批量插入成功");
    }
}
public static void main(String[] args) throws SQLException {
JDBCTest2 test2= new JDBCTest2();
        try {
            test2.isertBatch();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

**注意:如果是sql是查询语句,返回的是结果集,使用ResultSet去接收,若sql是插入或更新数据返回的则是int类型

PreparedStatement可以带参数,也可以不带参数