mysql8.0以上版本中: JDBC和Druid的配置

本文介绍了在MySQL8.0及以上版本中,如何配置JDBC连接以及使用Druid连接池进行数据库连接。详细阐述了jdbc.properties和druid.properties配置文件的编写,并提供了相应的数据库连接代码示例。

1. jdbc.properties配置文件的编写

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://ip:port/database?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123 

2. druid.properties配置文件的编写

druid.driverClassName = com.mysql.cj.jdbc.Driver
druid.url= jdbc:mysql://ip:port/database?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
druid.username = root
druid.password = 123
druid.maxActive=20

3. jdbc连接数据库的代码

class A{
        final String  USERNAME="root";
		final String PASSWORD="123";
		final String URL="jdbc:mysql://192.168.0.154:3306/book_db?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
		Class.forName("com.mysql.cj.jdbc.Driver");
		Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		Statement state = connection.createStatement();
		String sql="insert into book_tab(book_title,book_price) values('美少女战士',99.99)";
		state.executeUpdate(sql);
		System.out.println("添加成功");
		if(state!=null) {
			state.close();
		}
		if(connection!=null) {
			connection.close();
		}

    }

3. druid连接池连接数据库的代码

 		    Properties pro = new Properties();
			pro.load(new FileReader(Constants.PATH));//括号里面写上你的配置文件路径
			DruidDataSource ds = new DruidDataSource();
			ds.configFromPropety(pro);
			Connection conn = ds.getConnection();//获取连接
			PrepareStatement pst = conn.prepareStatement(sql);
			ResultSet rs=pst.executeQuery(); //执行查询有返回结果集
			while(rs.next()) {
				System.out.println(rs.getString(列名));
			}
			/*
			*完毕之后记得关闭所有连接,释放资源
			*/
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (conn != null) {
				conn.close();
			} 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值