java的jdbc使用

本文详细介绍了JDBC的基本使用,包括注册驱动、建立连接、执行SQL语句和关闭资源。接着讲解了如何封装JDBCUtils工具类以简化操作,以及如何在事务中使用JDBC。此外,还探讨了JDBC的批处理和数据库连接池的使用,特别是Druid连接池的配置和应用。最后,展示了如何封装增删改查方法和DAO类以提高代码复用性。
摘要由CSDN通过智能技术生成
jdbc使用方法
纲领:
  • 正常jdbc的连接
  • 封装JDBCUtils工具类(配置对象、第一步注册驱动、第二部连接对象是重复,所以封装成第一部分。后面关闭也重复对其封装成第三部分)
  • 使用事务的连接
  • jdbc的批处理
  • 数据库连接池的使用
  • 自己封装增删改查方法(将第三步的代码执行封装成增删改查方法)
  • 增删改查的框架DBUtils
  • 封装Dao类
简述步骤:
       ①先通过配置对象读取配置文件然后将配置变成变量
      ②注册驱动
      ③获取连接
      ④写sql语句存在变量
      ⑤创建执行对象
      ⑥将sql语句的占位符替换
      ⑦执行sql语句
      ⑧该获取什么结果怎么处理
      ⑨释放资源
一、正常的使用jdbc方法
完整步骤:
    准备工作:将java与mysql的连接jar包加入环境,并且创建一个配置文件里面包含(url,username,password,driver)为了创建properties对象。
    连接步骤:
  • ①注册驱动
使用Class.forName(driver)注册
使用的是反射机制,因为 Driver 接口的驱动程序类都包含了静态代码块,在这个静态代码块中,会调用 DriverManager.registerDriver() 方法来注册自身的一个实例,所以可以换一种方式来加载驱动。(即只要想办法让驱动类的这段静态代码块执行即可注册驱动类,而要让这段静态代码块执行,只要让该类被类加载器加载即可)
Class.forName(driver);
  • ②获取连接
使用DriverManager.getConnection(url,username,password)
将url和username和password给连接对象,创建连接对象
Connection connection=DriverManager.getConnection(url, username,  password);
  • ③ 执行语句
想要执行语句得先创建执行语句的对象(PreparedStatement),使用connection.preparedStatement(sql)创建
因为这个方法可以预编译,所以将sql语句先赋进去,然后语句中有占位符的话,就可以使用statement.setXX(index,value)。
String sql = "SELECT eid,ename,tel,gender,salary FROM t_employee WHERE ename = ?";
// 3、把带?的sql语句进行预编译
PreparedStatement pst = conn.prepareStatement(sql);
// 4、把?用具体的变量的赋值
pst.setString(1, name);
// 5、执行sql
ResultSet rs = pst.executeQuery();
while (rs.next()) {
int id = rs.getInt("eid");
String ename = rs.getString("ename");
String tel = rs.getString("tel");
String gender = rs.getString("gender");
double salary = rs.getDouble("salary");
System.out.println(id + "\t" + ename + "\t" + tel + "\t" + gender + "\t" + salary);
}
  • ④释放资源
    直接将对象调用close()方法。
完整代码:
package mysqltext;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;
import com.mysql.jdbc.Driver;
import com.mysql.jdbc.JDBC4CallableStatement;
public class text01 {
       public static void main(String[] args) throws SQLException, Exception {
             
             Scanner input = new Scanner(System.in);
             System.out.println("请输入姓名:");
             String name = input.nextLine();
             
             Properties info = new Properties();
             info.load(new FileInputStream("src\\jdbc.properties"));
             String driver = info.getProperty("driver");
             String url = info.getProperty("url");
             String username = info.getProperty("user");
             String password = info.getProperty("password");
             
             //注册驱动
             Class.forName(driver);
             
             //获取连接
             Connection connection = DriverManager.getConnection(url, username,  password);
             
             //写语句
             String sql = "SELECT eid,ename,tel,gender,salary FROM t_employee  WHERE ename = ?";
             // 3、把带?的sql语句进行预编译
             PreparedStatement pst = connection.prepareStatement(sql);
             // 4、把?用具体的变量的赋值
             pst.setString(1, name);
             // 5、执行sql
             ResultSet rs = pst.executeQuery();
             while (rs.next()) {
             int id = rs.getInt("eid");
             String ename = rs.getString("ename");
             String tel = rs.getString("tel");
             String gender = rs.getString("gender");
             double salary = rs.getDouble("salary");
             System.out.println(id + "\t" + ename + "\t" + tel + "\t" + gender  + "\t" + salary);
             }
             
             
             
             //关闭
             rs.close();
             pst.close();
             connection.close();
       }
       
}
二、封装JDBCUtils工具类
将配置对象和注册驱动封装在静态代码块(因为只需要一次就可以了)
将连接封装成一个方法,并try catch了一下
将关闭封装成一个方法,并try catch了一下
代码块:
package mysqltext;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
       static String url;
       static String username;
       static String password;
       static String driver;
       static {
             try {
                    Properties info = new Properties();
                    info.load(new FileInputStream("src//jdbc.properties"));
                    url=info.getProperty("url");
                    username=info.getProperty("user");
                    password=info.getProperty("password");
                    driver=info.getProperty("driver");
                    //注册驱动
                    Class.forName(driver);
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }
       }
       
       public static Connection getConnection(){
             try {
                    return DriverManager.getConnection(url, username, password);
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }
       }
       
       public static void close(ResultSet set,Statement statement,Connection  connection){
             try {
                    if(set!=null) {
                           set.close();
                    }
                    if(statement!=null) {
                           statement.close();
                    }
                    if(connection!=null) {
                           connection.close();
                    }
             } catch (SQLException e) {
                    throw new RuntimeException(e);
             }
       }
}
三、使用事务的连接
仅仅只是在第三步的执行代码里面去改变
步骤:
①开启事务
②执行代码快
③提交事务
伪代码:
            将连接和执行对象声明在外面
             try {
                    ①关闭事务
                    ②执行代码快
                    ③commit提交
             }catch(Exception e) {
                    如果报错就rollback
             }finally {
                    关闭
             }
代码块:
             Connection connection = null;
             PreparedStatement statement = null;
             //数据如下: name money(转账)
             //                  张三  10000
             //                  李四  10000
             try {
                    
                    //连接
                    connection=JDBCUtils.getConnection();
                    
                    connection.setAutoCommit(false);
                    String sql="update 表名 set money=?5000 where name=?";
                    statement = connection.prepareStatement(sql);
                    statement.setInt(1, 5000);
                    statement.setString(2, "张三");
                    statement.executeUpdate();
                    
                    statement.setInt(1, 15000);
                    statement.setString(2, "李四");
                    statement.executeUpdate();
                    
                    connection.commit();
             } catch (SQLException e) {
                    try {
                           connection.rollback();
                    } catch (SQLException e1) {
                           e1.printStackTrace();
                    }
             }finally {
                    //关闭
                    JDBCUtils.close(null, statement, connection);  
             }
四、jdbc的批处理
仅仅只是在第三步的执行代码里面去改变
步骤:
①先将url后面添加一下参数(?rewriteBatchedStatements=true),意思为直接批处理。
②批处理就三个方法,addBatch()、executeBatch()、clearBatch()。增加、执行、清空
代码:
statement = connection.prepareStatement("insert into admin values(null,?,?)");
             
             for(int i=1;i>50000;i++){
                    statement.setString(1, "zjx"+1);
                    statement.setString(2, "0000");
                    
                    statement.addBatch();
                    
                    if(i%1000==0) {
                           statement.executeBatch();
                           statement.clearBatch();
                    }
                    
             }
五、 数据库连接池的使用
连接步骤:
①导入jar包
②写配置文件
开源框架的使用步骤:
①导入jar包
②看帮助文档如何用
③调方法使用
代码:
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class TestDruid {
        static DataSource ds;
        static{
             Properties pro = new Properties();
             pro.load(new FileInputStream("src\\druid.properties"))//将配置文件读入
             ds = DruidDataSourceFactory.createDataSource(pro);//创建了一个带参数的druid连接池        
        }
       public static void main(String[] args) throws Exception {
            //直接将durid的配置文件和创建连接池封装,然后封装个连接对象方法,将连接对象放入
             Connection conn = ds.getConnection();//从连接池拿出一个连接对象
             
       }
}
配置文件内容:
driverClassName= com.mysql.jdbc.Driver
url= jdbc:mysql:// localhost :3306/ mytext ?rewriteBatchedStatements=true
username= root
password= 123456
initialSize= 10
minIdle= 5
maxActive= 20
maxWait= 5000
六、 自己封装增删改查方法
封装方法分为两步:
①将增删改封装为一个方法
②将查封装为一个方法
查的话,这个方法的返回值是一个对象,但是这个对象只能针对一个表,需要创建要查的表对象,作为返回值。
代码:
package mysqltext;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 此类用于封装通用的增删改查方法
* 功能:
* 1.执行增删改
* 2.执行查
*/
public class CRUDUtils {
       /**
        * 功能:增删改
        * 针对任何表的增删改
        * @return
        * @throws Exception
        */
       public static int update(String sql,Object...params){
             Connection connection = null;
             PreparedStatement statement = null;
             
             try {
                    connection = JDBCUtils.getConnection();
                    statement = connection.prepareStatement(sql);
                    for(int i=0;i<params.length;i++){
                           statement.setObject(i+1, params[i]);
                    }
                    int update = statement.executeUpdate();
                    return update;
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }finally {
                    JDBCUtils.close(null, statement, connection);
             }
       }
       /**
        * 功能:查询
        * 针对boys表的查询,查询单条
        * @param sql
        * @param params
        * @return
        */
       public static boys querySingle(String sql,Object...params){
             Connection connection = null;
             PreparedStatement statement = null;
             ResultSet set = null;
             
             try {
                    connection = JDBCUtils.getConnection();
                    
                    statement = connection.prepareStatement(sql);
                    for(int i=0;i<params.length;i++){
                           statement.setObject(i+1, params[i]);
                    }
                    
                    set = statement.executeQuery();
                    
                    if(set.next()) {
                           int id = set.getInt("id");
                           String boyName = set.getString("boyName");
                           int userCP = set.getInt("userCP");
                           boys bo = new boys(id,boyName,userCP);
                           return bo;
                    }
                    return null;
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }finally {
                    JDBCUtils.close(set, statement, connection);
             }
             
       }
       /**
        * 功能:查询
        * 针对boys表的查询,查询多条
        * @param sql
        * @param params
        * @return
        */
       public static List<boys> queryMulit(String sql,Object...params){
             Connection connection = null;
             PreparedStatement statement = null;
             ResultSet set = null;
             
             try {
                    connection = JDBCUtils.getConnection();
                    
                    statement = connection.prepareStatement(sql);
                    for(int i=0;i<params.length;i++){
                           statement.setObject(i+1, params[i]);
                    }
                    
                    set = statement.executeQuery();
                    
                    List<boys> list = new ArrayList<>();
                    while(set.next()) {
                           int id = set.getInt("id");
                           String boyName = set.getString("boyName");
                           int userCP = set.getInt("userCP");
                           boys bo = new boys(id,boyName,userCP);
                           list.add(bo);
                    }
                    return list;
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }finally {
                    JDBCUtils.close(set, statement, connection);
             }
             
       }
}
七、增删改查的框架DBUtils
核心:就在于创建对象然后调它的方法然后传参数就可以了。
增删改使用update方法,然后传(连接对象、sql语句、sql语句的参数)
查询使用query方法,然后传(连接对象、sql语句、”返回的数量的对象“、sql语句的参数)( 注意!!创建的返回值类一定要有空的构造方法
    ”返回的数量的对象“:一行为 new BeanHandler<>(Admin.class),多行为 new BeanListHandler<>(),一个值为new scalarHandler()
使用步骤:
①先创建连接对象
②创建QreryRunner对象
③直接使用对象的update或者
代码:
package mysqltext;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
public class TestDBUtils {
       /**
        * 测试增删改功能
        * @throws Exception
        */
       @Test
       public void testUpdate() throws Exception {
             
             Connection connection = JDBCUtils.getConnection();
             
             QueryRunner qr = new QueryRunner();
             int update = qr.update(connection, "insert into boys  values(?,?,?)",null,"hhh",900);
             System.out.println(update);
             
       }
       /**
        * 测试查询功能
        * @throws SQLException
        */
       @Test
       public void testQuery() throws SQLException {
             Connection connection = JDBCUtils.getConnection();
             //查询一行数据
             QueryRunner qr = new QueryRunner();
             boys boys = qr.query(connection, "select * from boys where id=1",  new BeanHandler<>(boys.class));
             System.out.println(boys);
             //查询多行数据
             List<boys> boy = qr.query(connection, "select * from boys", new  BeanListHandler<>(boys.class));
             for (boys boys2 : boy) {
                    System.out.println(boys2);
             }
             //查询一个数据
             Object boys2 = qr.query(connection, "select count(*) from boys",  new ScalarHandler());
             System.out.println(boys2);
       }
       
}
八、封装Dao类
写程序有三个层:实体类层、业务层、界面层
Dao类的定义:专门与数据库对接提供给业务层使用。其本意就是将增删改查方法封装起来。
步骤:有四个方法
    ①封装增删改方法
    ②封装单行数据的查方法
    ③封装多行数据的查方法
    ④封装单个值的查方法
代码:
package mysqltext;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
public class BasicDao {
       QueryRunner qr = new QueryRunner();
       public int update(String sql,Object...param) {
             Connection connection = null;
             try {
                    connection = JDBCUtils.getConnection();
                    int update = qr.update(connection, sql, param);
                    return update;
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }finally {
                    JDBCUtils.close(null, null, connection);
             }
       }
       
       public <T> T querySingle(String sql,Class<T> clazz,Object...param){
             Connection connection = null;
             try {
                    connection = JDBCUtils.getConnection();
                    return qr.query(connection, sql, new  BeanHandler<>(clazz),param);
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }finally {
                    JDBCUtils.close(null, null, connection);
             }
       }
       
       
       public <T> List<T> queryMulti(String sql,Class<T> clazz,Object...param){
             Connection connection = null;
             try {
                    connection = JDBCUtils.getConnection();
                    return qr.query(connection, sql, new  BeanListHandler<>(clazz),param);
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }finally {
                    JDBCUtils.close(null, null, connection);
             }
       }
       
       public Object scalarr(String sql,Object...param){
             Connection connection = null;
             try {
                    connection = JDBCUtils.getConnection();
                    return qr.query(connection, sql, new ScalarHandler(),param);
             } catch (Exception e) {
                    throw new RuntimeException(e);
             }finally {
                    JDBCUtils.close(null, null, connection);
             }
       }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值