JDBC



JDBC

是Java的API,各数据库厂商负责实现,我们只要用数据库驱动程序就好,这样就避免了使用不同数据库就要学习不同数据库的方法


JDBC对象及其方法

Connection:与数据库的交互

close()     //关闭数据库连接
commit()  //提交所有更改内容并释放该Connection对象锁定的资源
rollback()  //取消本轮事务中前面已经提交的更改
setAutoCommmit() //设置是否自动提交
preparedStatement()  //基于本连接对象,创建PreparedStatement对象
createStatement() //基于本Connection对象,创建Statement对象
prepareCall()    //存储过程

Statement:向数据库发送Sql语句

executeQuery(String sql) //查询,返回结果集
executeUpdate(String sql) //增删改,返回影响条数
//任意sql语句都可以,查询是true,false是增删
//getResultSet()获取结果集,getUpdateCount()获取影响条数
execute(String sql) 
addBatch(String sql) //把多条的sql语句放进同一个批处理中
executeBatch() //向数据库发送一批sql语句执行
clearBatch()

PreparedStatement:继承Statement,预编译Sql语句存储在本对象中,防止SQL注入,之后的参数不再编译

//获取到自动主键列的值
resultSet rs= preparedStatement.getGeneratedKeys();
if (rs.next()) {
    int id = rs.getInt(1);
    System.out.println(id);
}

ResultSet:Sql语句的执行结果,当生成ResultSet的Statement对象要关闭或者重新执行或是获取下一个ResultSet的时候,ResultSet对象也会自动关闭。

getObject(String columnName) //获取任意类型的数据
getString(String columnName) //获取指定类型的数据【各种类型,查看API】

//对结果集进行滚动查看的方法
next()
Previous()
absolute(int row)
beforeFirst()
afterLast()


步骤

  1. 导入驱动包
  2. 加载驱动程序
  3. 获取连接
  4. 获取执行SQL语句的对象
  5. 执行SQL语句
  6. 关闭连接
public class DBUtil {
    
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/test";
    private static String username = "root";
    private static String password = "";
    
    static{
         try {
             //注册驱动
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    
    public static Connection getConnection() throws SQLException {
        //获取数据库连接
        return DriverManager.getConnection(url,username,password);
    }
    
    public static void closeConnection(Connection connection, Statement statement,PreparedStatement preparedstatement ,ResultSet resultSet){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedstatement != null) {
            try {
                preparedstatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}


批处理

Statement,返回一个int[]数组,该数组代表各句SQL的返回值

//可以处理不同语句
String sql1 = "UPDATE <表名> SET name='Howl' WHERE id='1'";
String sql2 = "INSERT INTO <表名> (id, name) VALUES ('1','Howl')";

//将sql添加到批处理
statement.addBatch(sql1);
statement.addBatch(sql2);

//执行批处理
statement.executeBatch();

//清空批处理的sql
statement.clearBatch();

PreparedStatement

//只能处理同类型语句


事务

try{
    //关闭自动提交
    conn.setAutoCommit(false);
    
    //账号1减去50
    String sql1 = "UPDATE account SET money = money-50 WHERE id = 1";
    PreparedStatement ps1 = conn.prepareStatement(sql1);
    ps1.executeUpdate();
    
    //报错
    int a = 1 / 0;
    
    //账号2加50
    String sql2 = "UPDATE account SET money = money+50 WHERE id = 2";
    PreparedStatement ps2 = conn.prepareStatement(sql2);
    ps2.executeUpdate();
    
    //提交
    conn.commit();
    //关闭事务,防止后面使用不提交
    conn.setAutoCommit(true);
} catch (SQLException e) {
    try {
        //回滚
        conn.rollback();
        conn.setAutoCommit(true);
    } catch (SQLException e1) {
        e1.printStackTrace();
    }
}


存储过程

调用存储过程的语法:

{call [(,, ...)]}

调用函数的语法:

{?= call [(,, ...)]}
public class Test {

    public static void main(String[] args) {
        Connection connection = null;
        CallableStatement callableStatement = null;

        try {
            connection = JdbcUtils.getConnection();

            callableStatement = connection.prepareCall("{call demoSp(?,?)}");

            callableStatement.setString(1, "nihaoa");

            //注册第2个参数,类型是VARCHAR
            callableStatement.registerOutParameter(2, Types.VARCHAR);
            callableStatement.execute();

            //获取传出参数[获取存储过程里的值]
            String result = callableStatement.getString(2);
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                callableStatement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}    




你可能感兴趣的:(JDBC)