数据库的连接和操作

本文参考资料:点击打开链接

目录

一、JDBC操作数据库

二、QueryRunner操作数据库

三、C3P0连接池

四、DBCP连接池


一、JDBC操作数据库

    1.jdbc的4大步骤

        (1)注册驱动

        (2)获得连接

        (3)获得数据库操作对象(一般使用PreparedStatement)

        (4)定义sql

        (5)执行sql

        (6)获取结果集

     2.jdbc实例

​
        Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;	
		try {
            //1.注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			
            //2.获得连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名","用户名","密码");
			
            //3.定义sql
			String sql = "select * from 表名";

            //4.获取数据库操作对象			
			ps = conn.prepareStatement(sql);

			//5.执行sql
			rs = ps.executeQuery();

            //4.获取结果集			
			while(rs.next()){
				System.out.println(rs.getInt(1)+"---"+rs.getString(2)+"---"+rs.getString(3));
			}

​

二、QueryRunner操作数据库

    1.ResultSetHandler类型

    

    2.代码实现

                //1.实例化时加入dataSource参数
		QueryRunner qr = new QueryRunner(c3p0Utils.getDataSource());
		String sql = "select * from t_user where id=?";
		User user1 = qr.query(sql, new BeanHandler<User>(User.class),2);
		//2.query()方法中加入连接
		QueryRunner qr2 = new QueryRunner();
		String sql2 = "select * from t_user where id=?";
		User user2 = qr2.query(c3p0Utils.getConnection(),sql, new BeanHandler<User>(User.class),3);
		System.out.println(user1+"\n"+user2);

三、C3P0连接池

    1.配置c3p0配置文件 

       简单的只需要配置default-config默认配置,如有需要,可以在格外添加,命名为named-config,并加上name属性。

​
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	
	<default-config>
		<property name="user">root</property>
		<property name="password">XXX</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/db_user</property>
	</default-config>
	
	<named-config name="conn_2">
		<property name="user">root</property>
		<property name="password">XXX</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/db_ssm_crud</property>
	</named-config> 
</c3p0-config>

​

    2.c3p0Utils

public class c3p0Utils {
	
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	
	//获得连接池
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	//获得连接
	public static Connection getConnection(){
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

3.依赖jar包

c3p0 —— https://mvnrepository.com/artifact/com.mchange/c3p0 

mchange-commons-java —— https://mvnrepository.com/artifact/com.mchange/mchange-commons-java

mysql-connection-java —— https://mvnrepository.com/artifact/mysql/mysql-connector-java

版本视情况而定,一般选usages大的。

四、DBCP连接池

1.DBCP(DataBase connection pool)数据库连接池是 apache 上的一个Java连接池项目。DBCP通过连接池预先同数据库建立一些连接放在内存中(即连接池中),应用程序需要建立数据库连接时直接到从接池中申请一个连接使用,用完后由连接池回收该连接,从而达到连接复用,减少资源消耗的目的。

2.配置文件dbConfig.properties

#数据库基本信息配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_user?useUnicode=true&characterEncoding=UTF8
username=root
password=123456

3.DBCPUtil

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
public class DBCPUtil {
    private static DataSource dataSource;
    static{
        try {
            InputStream is = DBCPUtil.class.getClassLoader().getResourceAsStream("dbconfig.properties");
            Properties props = new Properties();
            props.load(is);
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public static DataSource getDataSource(){
        return dataSource;
    }
    
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

4.依赖jar包

commons-dbcp2-2.1.1.jar —— https://mvnrepository.com/artifact/org.apache.commons/commons-pool2

commons-logging-1.2.jar —— https://mvnrepository.com/artifact/commons-logging/commons-logging

commons-pool2-2.4.2.jar —— https://mvnrepository.com/artifact/org.apache.commons/commons-pool2

具体版本视情况而定

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值