超详细JDBC学习

JDBC

1.1 介绍什么是JDBC

​ JDBC又叫数据库连接,顾名思义就是把应用程序(java)和数据库相连接。JDBC 提供一套规范的接口,这样的好处就是为了减少各个数据库接口的参差不齐(比如mysql一个接口,oracle一个接口),使用JDBC后,无论mysql 还是oracle都是用统一的接口。

1.2 JDBC连接的步骤

先下载对应的jar包 ,一定要下对版本,(看mysql的版本号)

mysql-connector-java-8.0.11.jar

一共七大步骤;

  • 注册启动

      Class.forName();   //这边注意  mysql8.0以上的要用 com.mysql.cj.jdbc.Driver  mysql8.0以下的用com.mysql.jdbc.Driver
    
  • 设置连接

     Connection con = DriverManager.getConnection("jdbc:mysql://域名:端口号/数据库名字", "登陆数据库的用户名", "密码");
    
  • 定义数据库的语句

 String sql = 数据库的增删改查语句(CRUD);             //例如 "select * from students"
  • 获取执行mysql的对象(statement)这里先介绍statement

     Statement sta = con.createStatement();
    
  • 执行mysql语句

    ​ 增删改用到

    int count =sta.executeUpdate(sql);
    

    ​ 查用到

      ResultSet cout = sta.executeQuery(sql);
    
  • 判断是否操作成功

    查用到

      while (cout.next()) {
                    System.out.print(cout.getString("name") + " ");
                    System.out.print(cout.getString("age") + " ");
                    System.out.print(cout.getString("height") + " ");
                    System.out.print(cout.getString("sex") + " ");
                    System.out.println();
                }
    

    增删改用到

    if(count>0){
      System.out.print( "操作成功 ");
    }else{
    System.out.print( "操作失败 ");
    }
    
  • 释放资源

      con.close();
      sta.close();
      rs.close();
    

    完整代码(statement获取mysql对象)

    mysql 8.0以上的要注意时区,在url添加serverTimezone=GMT%2B8

    驱动也不同com.mysql.cj.jdbc.Driver

工具类:(代码形式)
    
    public class JDBC_demo {
    private static String  name = null;
    private static String url = null;
    private static String user = null;
    private static String password = null;

        //代码形式设置参数
 static {
    name = "com.mysql.cj.jdbc.Driver";
    url = "jdbc:mysql://localhost:3306/jk?serverTimezone=GMT%2B8&useSSL=false";
    user = "用户名";
    password = "密码";
    try {
        //注册驱动
        Class.forName(name);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

/*获取数据库连接*/
    public static Connection getconnection() throws SQLException {

        return DriverManager.getConnection(url,user,password);

    }
   //释放资源
    public static void Release(Connection connection, Statement statement){
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    public static void Release(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }



        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

}

​ 采用配置文件的方法(comfigura.properties)

driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jk?serverTimezone=GMT%2B8&useSSL=false
username=用户名
password=密码

//工具类

DBUtils.java

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    private static String driver;
    // 数据库连接地址
    private static String url;
    // 数据库用户名
    private static String username;
    // 数据库密码
    private static String password;

   
    static {
        try {
            // 加载comfigura.properties配置文件中的数据库连接信息  读文件
            InputStream in = DBUtils.class.getClassLoader().getResourceAsStream("comfigura.properties");
            Properties prop = new Properties();
            // 加载文件
            prop.load(in);

            driver = prop.getProperty("driverName");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");

            // 使用静态代码块加载数据库驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭资源
     * @param
     * @param stmt
     * @param conn
     */
    public static void close( Statement stmt, Connection conn) {
        try {

            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Statement stmt, Connection conn,ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
       } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

增删改的代码都一样的,只是SQL语句不一样而已,

public class demo {

    public static void main(String[] args) {

        Connection connection = null;
        Statement statement = null;

        try {
            connection = JDBC_demo.getconnection();
            statement = connection.createStatement();
			// 增加 insert into students values(('林俊',40,'176.0','man'));
             //	修改 update students set height=175.00 where name = '周杰'
            String sql = "delete from students where name='林俊'";

            int cout = statement.executeUpdate(sql);

            if (cout>0){
                System.out.println("删除成功");
            }
            else {
                System.out.println("删除失败");
            }




        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBC_demo.Release(connection,statement);

        }
    }

}

查的代码

public class demo {

    public static void main(String[] args) {

        Connection connection = null;
        Statement  statement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBC_demo.getconnection();
            //获取mysql执行的对象
            statement = connection.createStatement();

            String sql = "select * from students";
			//查找用ResultSet对象  statement.executeQuery(sql)
             //增删改用int, statement.executeUpdate(sql)
             resultSet = statement.executeQuery(sql);
            if(resultSet!=null){
                System.out.println("查询成功,查询结果如下:");
                while (resultSet.next()){
                    System.out.print(resultSet.getString("name")+" ");
                    System.out.print(resultSet.getInt("age")+" ");
                    System.out.print(resultSet.getString("height")+" ");
                    System.out.print(resultSet.getString("sex"));
                    System.out.println("");
                }

            }else{
                System.out.println("查询失败");
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
          JDBC_demo.Release(connection,statement,resultSet);
        }
    }

}

但是statement有一个缺点,就是数据库容易被注入漏洞,用statement对象的话,还有写一个防止SQL注入的代码。但是用PreparedStatement就可以避免SQL注入,其中PreparedStatement的性能也比statement快一点。

其中preparestatement和statement不同之处,就是preparestatement要先进行预处理,用占位符代替变量。

预处理

   preparedStatement = connection.prepareStatement(sql);

给变量赋值

preparedStatement.setString(占位符位置,"占位符需要的值");

​ PrepareStatement的增删改

public class prepareStatement_src_demo2 {

    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //数据库连接 跟statement没有区别
            connection = JDBC_demo.getconnection();
            //变量用占位符表示
            //增删改
            // 改 update land set password=? where username=?
            // 增 insert into land values(?,?,?)
            String sql = "delete from land where username=?";
            /*对SQL语句进行预处理*/
            preparedStatement = connection.prepareStatement(sql);
            //对SQL语句赋值 1代表是第一个?的意思
            preparedStatement.setString(1,"小芹");
            //执行SQL语句
            int cout = preparedStatement.executeUpdate();
            if (cout>0){
                System.out.println("删除成功");
            }
            else {
                System.out.println("删除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            JDBC_demo.Release(connection,preparedStatement);
        }
    }
}

PrepareStatement的查

public class prepareStatement_src_demo4 {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtils.getConnection();

            String sql = "select  username,password from land ";

            preparedStatement = connection.prepareStatement(sql);
			//preparedStatement.executeQuery();
            resultSet = preparedStatement.executeQuery();

            if (resultSet != null) {
                System.out.println("查询成功--查询的结果如下:");
                while (resultSet.next()) {
                    System.out.print(resultSet.getString("username") + " ");
                    System.out.print(resultSet.getString("password") + " ");
                   /* System.out.print(resultSet.getString("xinxi") + " ");*/
                    System.out.println("");
                }

            }
            else {
                System.out.println("查询失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            DBUtils.close(preparedStatement, connection, resultSet);
        }
    }
}
1.3 事务

事务简称(ACID),事务发生只有两种情况,要么成功,要么失败。

原子性(Atomicity)
原子性是指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生。
一致性(Consistency)
事务前后数据的完整性必须保持一致。
隔离性(Isolation)
事务的隔离性是多个用户并发访问数据库时,数据库为每一个用户开启的事务,不能被其他事务的操作数据所干扰,多个并发事务之间要相互隔离。
持久性(Durability)
持久性是指一个事务一旦被提交,它对数据库中数据的改变就是永久性的,接下来即使数据库发生故障也不应该对其有任何影响

事务管理 又可以分为三方面

/采用事务管理可以更好地保护数据安全/

  • 1.事务开启 setAutoCommit(false)
  • 2.事务回滚 rollback()
  • 3.事务提交 commit()

下面是银行转账的例子:


public class JDBC_demo1 {

    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement pre = null;
        try {
            connection = JDBC_demo.getconnection();
            //数据库时默认自动打开事务并提交,这里要设置手动开启
            connection.setAutoCommit(false);
            String sql = "update transfer set money=money+? where username = ?";
            pre = connection.prepareStatement(sql);
            pre.setString(1,"-1000");
            pre.setString(2,"A");
            pre.executeUpdate();

            pre.setString(1,"1000");
            pre.setString(2,"B");
            pre.executeUpdate();
            System.out.println("转账成功");
            //事务提交
            connection.commit();
        }catch (Exception e){
            try {
                /*如果报错,就会回滚事务,倒回到原样。*/
               connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {
            JDBC_demo.Release(connection,pre);
        }
    }

}

数据源

现在的数据库层出不穷,但是现在中大型公司用的有三个主要数据源

  • DBCP
  • C3P0
  • Druid

DBCP数据源要下载对应的jar包(切记版本一定要对,跟mysql的版本对的上)

commons-dbcp2-2.7.0.jar

commons-logging-1.2.jar

commons-pool2-2.8.0.jar

DBCP
/*DBCP采用池化技术的优点:
*   性能提高
*   代码简洁了一点。
*   采用池化技术不用注册驱动和连接赋值了。这些都可以省掉,直接在DBCP连接池里用*/

配置文件Connection_DBCP.properties:

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jk?serverTimezone=GMT%2B8&useSSL=false
username=用户名
password=密码
#初试连接数
initialSize=30
#最大活跃数
maxActive=30
#最大空闲连接数
maxIdle=10
#最小空闲连接数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1

工具类 DBCPconfigura.java

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBCPconfigura {

    private static BasicDataSource dataSource;
    /*CBCP采用池化技术的优点:
    *   性能提高
    *   代码简洁了一点。
    *   采用池化技术不用注册驱动和连接赋值了。这些都可以省掉,直接在DBCP连接池里用*/
    static {
        try {
            // 加载配置文件中的数据库连接信息  读文件
            InputStream in =DBCPconfigura.class.getClassLoader().getResourceAsStream("Connection_DBCP.properties");
            Properties prop = new Properties();
            // 加载文件
            prop.load(in);
			//不用注册驱动和连接赋值,主要这一句就行了。
            dataSource = BasicDataSourceFactory.createDataSource(prop);

            // 使用静态代码块加载数据库驱动

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws Exception {

        return dataSource.getConnection();
    }
    /**
     * 关闭资源
     */
    public static void close( Statement stmt, Connection conn) {
        try {

            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(Statement stmt, Connection conn,ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

实战类 prepare_insert.java(增删改查都差不多的)

import java.sql.Connection;
import java.sql.PreparedStatement;

public class prepare_insert {
    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement pre = null;

        try {
            connection = DBCPconfigura.getConnection();
            String sql = "insert into land values(?,?,?)";
            /*对SQL语句进行预处理*/
            pre = connection.prepareStatement(sql);
            /*parameterlndex  是表示第几个问号的意思*/
            pre.setString(1,"小符");
            pre.setString(2,"12346");
            pre.setString(3,"计算机学院");
            /*执行SQL语句*/
            int cout = pre.executeUpdate();

            if(cout>0){
                System.out.println("插入成功");
            }
            else {
                System.out.println("修改成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            DBCPconfigura.close(pre, connection);
        }
    }
}
C3P0

C3P0数据源需要下载的jar包(切记要下载对版本)

c3p0-0.9.5.5.jar

mchange-commons-java-0.2.15.jar

C3P0采用的是xml的配置方式,一定要小心xml的配置,因为坑太多了,注意不能留空格,&后面加amp;

一、C3P0配置文件名字一定是c3p0-config.xml;(特别注意)我就在这个坑踩了三个多小时

二、c3p0-config.xml放在src根目录下面;

配置文件C3P0-config.xml


<c3p0-config>
    //默认的配置
    <default-config>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/jk?serverTimezone=GMT%2B8&useSSL=falseproperty>
    <property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
    <property name="user">用户名property>
    <property name="password">密码property>
        
        <property name="acquireIncrement">3property>
        
        <property name="acquireRetryAttempts">30property>
        
        <property name="initialPoolSize">10property>
        
        <property name="minPoolSize">5property>
        
        <property name="maxPoolSize">15property>
        
        <property name="maxIdleTime">6000property>

    default-config>
    <named-config name="mysql">
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jk?serverTimezone=GMT%2B8&useSSL=falseproperty>
        <property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
        <property name="user">用户名property>
        <property name="password">密码property>
        
        <property name="acquireIncrement">3property>
        
        <property name="acquireRetryAttempts">30property>
        
        <property name="initialPoolSize">10property>
        
        <property name="minPoolSize">5property>
        
        <property name="maxPoolSize">15property>
        
        <property name="maxIdleTime">6000property>

    named-config>
c3p0-config>

工具类C3P0_config.java:

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class C3P0_config {
    private static ComboPooledDataSource dataSource;
    /*采用C3P0池化技术的优点:
     *   性能提高
     *   代码简洁了一点。
     *   不需要读文件,但是xml的配置文件一定要注意书写,不然很容易报错。*/
    static {
        try {
            
            dataSource = new  ComboPooledDataSource("mysql");

            // 使用静态代码块加载数据库驱动

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws Exception {

        return dataSource.getConnection();
    }
    /**
     * 关闭资源

     */
    public static void close(Statement stmt, Connection conn) {
        try {

            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Statement stmt, Connection conn, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

实战类prepare_delete.java(增删改查都一样):

import java.sql.Connection;
import java.sql.PreparedStatement;

/*prepareStatement删除*/
public class prepare_delete {

    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = C3P0_config.getConnection();
            String sql = "delete from land where username=?";
            /*对SQL语句进行预处理*/
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,"小符号");
            int cout = preparedStatement.executeUpdate();
            if (cout>0){
                System.out.println("删除成功");
            }
            else {
                System.out.println("删除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            C3P0_config.close(preparedStatement, connection);
        }
    }

}
Druid(德鲁伊)

Druid数据源(德鲁伊)是阿里的数据源,需下载的jar包(切记要下载对版本)

druid-1.1.21.jar

配置文件Druid_config.properties:

driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jk?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
username=用户名
password=密码

# JDBC Pool
#连接池建立时创建的初始化连接数
jdbc.pool.init=10
#连接池中最小空闲连接数
jdbc.pool.minIdle=5
#连接池中最大的活跃连接数
jdbc.pool.maxActive=20
#最长等待时间(毫秒)
maxWaitMillis=1000

validationQuery=select 1
testOnBorrow=true
testWhileIdle=true

工具类Druid_config.java

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Druid_config {
    private static DataSource dataSource;
    /*CBCP采用池化技术的优点:
     *   性能提高
     *   代码简洁了一点。
     *   采用池化技术不用注册驱动和连接赋值了。这些都可以省掉,直接在DBCP连接池里用*/
    static {
        try {
            // 加载配置文件中的数据库连接信息  读文件
            InputStream in = Druid_config.class.getClassLoader().getResourceAsStream("Druid_config.properties");
            Properties prop = new Properties();
            // 加载文件
            prop.load(in);
			//三大数据源的区别 
             dataSource = DruidDataSourceFactory.createDataSource(prop);

            // 使用静态代码块加载数据库驱动

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws Exception {

        return dataSource.getConnection();
    }

    /**
     * 关闭资源

     */
    public static void close(Statement stmt, Connection conn) {
        try {

            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Statement stmt, Connection conn, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

实战类prepareSelect.java 查找 :

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class prepareSelect {

    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = Druid_config.getConnection();

            String sql = "select * from land";

            preparedStatement = connection.prepareStatement(sql);

            resultSet = preparedStatement.executeQuery();

            if (resultSet != null) {
                System.out.println("查询成功--查询的结果如下:");
                while (resultSet.next()) {
                    System.out.print(resultSet.getString("username") + " ");
                    System.out.print(resultSet.getString("password") + " ");
                   System.out.print(resultSet.getString("xinxi") + " ");
                    System.out.println("");
                }

            }
            else {
                System.out.println("查询失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            Druid_config.close(preparedStatement, connection, resultSet);
        }
    }

}

DButils

DBUtils简化了JDBC的开发步骤,使得我们可以用更少量的代码实现连接数据库的功能,同时也不会影响程序的性能

减少冗余代码的产生,像预处理,数据库连接这些。

主要用到QueryRunner这个核心类

下载好对应的jar包

druid-1.1.21.jar

DButils的工具类也很简单

DButils_config.java(但需要有C3P0的配置文件)

import com.mchange.v2.c3p0.ComboPooledDataSource;
/*工具类DButils已经封装好
1 数据库驱动
2 数据库连接
3 预处理
4 释放资源

只需要传入SQL语句和SQL属性值*/
public class DButils_config {
    private static ComboPooledDataSource dataSources;

    static {
        /*获取到配置文件的参数*/
        dataSources = new ComboPooledDataSource();
    }
    //连接C3P0的数据源
    public static ComboPooledDataSource getDataSource(){
        return dataSources;
    }

}

增删改代码如下

​ example.java

import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import java.sql.SQLException;

public class example {

    @Test
    /*修改*/
    public void update() throws Exception {
		//核心类  实现连接数据源
        QueryRunner runner = new QueryRunner( DButils_config.getDataSource());
        int count =  runner.update("update land set password=? where username=?","1008611","A");
          /*成功的话 count会返回1 失败的话会返回-1*/
        if (count>0){
            System.out.println("修改成功");
        }else {
            System.out.println("修改失败");
        }
    }
    @Test
    /*插入*/
        public void insert() throws SQLException {
            QueryRunner runner = new QueryRunner(DButils_config.getDataSource());
            int count = runner.update("insert into land values(?,?,?)","B","13800138000","经管学院");
        if (count>0){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }
    }

    @Test
    /*删除*/
    public void delete() throws Exception {
        QueryRunner runner = new QueryRunner(DButils_config.getDataSource());
        int count = runner.update("delete from land where username=?","小花");
     
        if (count>0){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }

}

查询代码在开发中应用和广泛

​ 查询代码有很多种 第一种: ArrayHandlerArrayListHandler

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class example02  {
/*ArrayHandler和ArrayListHandler*/
    @Test
    /*查询单条语句,将其封装到数组中,*/
    public void select() throws SQLException {

        QueryRunner runner = new QueryRunner(DButils_config.getDataSource());
        Object[] query = runner.query("select * from land where username=?", new ArrayHandler(), "A");
        for (Object o : query) {
            System.out.print(o + " ");

        }

    }

    @Test
    /*查询多条语句 将每条语句封装到数组中object[],再将objec[]封装到list中*/
    public void LotSelect() throws SQLException {
        /*核心类*/
        QueryRunner runner = new QueryRunner(DButils_config.getDataSource());
        List<Object[]> query = runner.query("select * from land", new ArrayListHandler());
        String username="小思",password="1315";
        /*集合遍历是一行一行的输出*/
        //这里我试着看能不能匹配数据库中的 小思 这个名字
        for (Object[] objects : query) {
            System.out.println(Arrays.toString(objects));
            for (int i = 0; i < objects.length; i++) {
                if (objects[i].equals("小思")) {
                    for (Object str : objects) {
                        if (password.equals(str)){
                            System.out.println("用户名和密码匹配成功");
                        }
                    }
                        }
                    }
                }
            }
        }


(这个查询方法重要) BeanHandlerBeanListHandler 将查询到的数据封装到Javabean中


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.List;

public class im_example {
/*BeanHandler 和 BeanListHandler*/
    @Test
    /*将查询好的单条数据封装到Javabean中*/
    public void im_select() throws SQLException {

        QueryRunner runner = new QueryRunner(DButils_config.getDataSource());
        dbutils query = runner.query("select * from land where username=?", new BeanHandler<dbutils>(dbutils.class), "小花");
        System.out.println(query);
    }


    @Test
    public void im_LotSelect() throws SQLException {

        QueryRunner runner = new QueryRunner(DButils_config.getDataSource());
        List<dbutils> query = runner.query("select * from land", new BeanListHandler<dbutils>(dbutils.class));
        for (dbutils dbutils : query) {
            System.out.println(dbutils);
        }

    }
}

你可能感兴趣的:(超详细JDBC学习)