Java的JDBC

JDBC步骤

数据库JDBC驱动程序网址
mysql8com.mysql.cj.jdbc.Driverjdbc:mysql://hostname:3306/databaseName? serverTimezone=UTC
mysqlcom.mysql.jdbc.Driverjdbc:mysql://hostname:3306/databaseName
oracleoracle.jdbc.driver.OracleDriveroracle.jdbc.driver.OracleDriver
db2COM.ibm.db2.jdbc.net.DB2Driverjdbc:db2:hostname:port Number / databaseName
sybasecom.sybase.jdbc.SybDriverjdbc:sybase:Tds:hostname:port Number / databaseName

一、加载驱动

①使用Class.forName():

try {
    Class.forName(驱动包位置);
} catch (ClassNotFoundException ex) {
    
}

②使用DriverManager.registerDriver()

try {
    Driver myDriver = new 驱动包位置();
    DriverManager.registerDriver( myDriver );
} catch (SQLException ex) {
    
}

二、获得链接

使用DriverManager.getConnection()方法。

getConnection(String url)
getConnection(String url,Properties properties)
getConnection(String url,String user,String password)
String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&useUnicode=true&serverTimezone=UTC";
String user = "username";
String password = "password"
Connection connection= DriverManager.getConnection(url , user , password);

三、获得状态通道

(1)状态通道版本

Statement statement = null;
try {
    statement = conn.createStatement( );
}
catch (SQLException e) {

}
finally {

}

(2)预状态通道版本

PreparedStatement preparedStatement = null;
try {
    String SQL = "Update Employees SET age = ? WHERE id = ?";
    preparedStatement = conn.prepareStatement(SQL);
    preparedStatement.setInt(1, int类型数据);    //此处从1开始
}
catch (SQLException e) {

}
finally {

}

四、执行SQL

boolean execute(String SQL)
//如果可以检索到ResultSet对象,则返回一个布尔值true; 否则返回false。使用此方法执行SQL DDL语句或需要使用真正的动态SQL时。
int executeUpdate(String SQL)
//返回受SQL语句执行影响的行数。使用此方法执行预期会影响多个行的SQL语句,例如INSERT,UPDATE或DELETE语句。
ResultSet executeQuery(String SQL)
//返回一个ResultSet对象。当您希望获得结果集时,请使用此方法,就像使用SELECT语句一样。

五、处理Result结果集

resultSet.getInt(表列名);

六、关闭资源

if (connection != null) {
    connection.close();
}

七、事务处理

connection.setAutoCommit(false);        
//启动手动事务
connection.commit();
//事务提交
conneciton.rollback();
//事务回滚

定义工具类

public class DbUtils {
    //1.定义需要的工具类对象
    private Connection connection = null;
    private PreparedStatement preparedStatement = null;
    protected ResultSet resultSet = null;
    private int cnt = 0;                     //受影响的行数
    private String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&useUnicode=true&serverTimezone=UTC";
    private String username = "root";
    private String password = "123456";
    //2.加载驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //3.获得连接
    private Connection getConnection() {
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }
    //4.创建通道
    private PreparedStatement getPreparedStatement(String sql) {
        try {
            getConnection();    //insert into users values(?, ?, ?, ?)
            preparedStatement = connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return preparedStatement ;
    }
    //5.给占位符赋值 
    private void setParams(List list) {
        try {
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    preparedStatement.setObject(i+1, list.get(i));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //6.增删改
    protected int update(String sql, List paramsList){
        try {
            getPreparedStatement(sql);
            setParams(paramsList);
            cnt = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return cnt ;
    }
    //7.查询
    protected ResultSet query(String sql,List list){
        try {
            getPreparedStatement(sql);
            setParams(list);
            resultSet = preparedStatement.executeQuery();
            return resultSet ;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
    //8.关闭资源
    protected void closeAll(){
        try {
            if (resultSet  != null) {
                resultSet .close();
            }
            if (preparedStatement!= null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

properties文件操作

一、properties文件特点:键值对

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名称
user=root
password=123456

二、读取properties文件

①方式一:

InputStream inputStream = 当前类名.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
dirverName = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("user");
password = properties.getProperty("password")

②方式二:

ResourceBundle bundle = ResourceBundle.getBundle("db");
driver = bundle.getString("driver");
url = bundle.getString("url");
username = bundle.getString("user");
password = bundle.getString("password");

连接池

DBCPC3P0Druid
最小连接数mindle(0)minPoolSize(3)mindle(0)
初始化连接数initialSize(0)initialPoolSize(3)initialSize(0)
最大连接数maxTotal(8)maxPoolSize(15)maxActive(8)
最大等待时间maxWaitMillis(毫秒)maxldleTime(0秒)maxWait(毫秒)

一、DBCP

(1)硬编码方式

public void testHard() throws SQLException {
    BasicDataSource source = new BasicDataSource();
    source.setDriverClassName("com.mysql.jdbc.Driver");
    source.setUrl("jdbc:mysql://localhost:3306/数据库名");
    source.setUsername(账号);
    source.setPassword(密码);
    Connection connection = source.getConnection();
    String sql = "select * from student";
    Statement createStatement = connection.createStatement();
    ResultSet executeQuery = createStatement.executeQuery(sql);
    while (executeQuery.next()) {
        System.out.println(executeQuery.getString(2));
    }
    connection.close();
}

(2)软编码方式

①properties文件配置

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名
username=账号
password=密码
#<!-- 初始化连接 -->
initialSize=10
#<!-- 最大连接数量 -->
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->

②Java代码实现

ResourceBundle bundle = ResourceBundle.getBundle("db");
String driverClass = bundle.getString("driverclass");
String url = bundle.getString("url");
String username = bundle.getString("uname");
String password = bundle.getString("upass");
String init=bundle.getString("initsize");
BasicDataSource datasource = new BasicDataSource();
datasource.setDriverClassName(driverClass);
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setInitialSize(Integer.parseInt(init));

二、C3P0

C3P0是在外部添加配置文件,工具直接进行应用,因为直接引用,所以要求固定的命名和文件位置。

文件位置: src        文件命名:c3p0-config.xml/c3p0-config.properties

文件配置:

<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
    <!-- 默认配置,如果没有指定则使用这个配置 -->
    <default-config>
        <!-- 基本配置 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day2</property>
        <property name="user">root</property>
        <property name="password">111</property>
        <!--扩展配置-->
        <!-- 连接超过30秒报错-->
        <property name="checkoutTimeout">30000</property>
        <!--30秒检查空闲连接 -->
        <property name="idleConnectionTestPeriod">30</property>
        <property name="initialPoolSize">10</property>
        <!-- 30秒不适用丢弃-->
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>
    </default-config>
    <!-- 命名的配置 -->
    <named-config name="abc">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day2</property>
        <property name="user">root</property>
        <property name="password">111</property>
        <!-- 如果池中数据连接不够时一次增长多少个 -->
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">20</property>
        <property name="minPoolSize">10</property>
        <property name="maxPoolSize">40</property>
        <property name="maxStatements">20</property>
        <property name="maxStatementsPerConnection">5</property>
    </named-config>
</c3p0-config>

代码实现:

ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
Connection connection = comboPooledDataSource.getConnection();

三、德鲁伊(Druid)

同样需要有properties文件的配置。

Properties properties = new Properties();
properties.load(DruidUtils.class.getClassLoader().getResourceAsStream("文件名.properties"));
DruidDataSource druidDataSource = new DruidDataSource();
//设置驱动类全称
druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
//设置连接的数据库
druidDataSource.setUrl(properties.getProperty("url"));
//设置用户名
druidDataSource.setUsername(properties.getProperty("username"));
//设置密码
druidDataSource.setPassword(properties.getProperty("password"));
//设置最大连接数量
druidDataSource.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
//获得连接
Connection connection = druidDataSource.getConnection();

写在最后:

以上内容为博主学习相关课程所作笔记,方便之后复习时查看,若有侵权等行为私聊我删除。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值