使用 jdbc 连接 mysql 数据库

本文介绍了如何使用jdbc原生方式连接MySQL数据库,强调了通过db.properties文件存储连接配置的灵活性,便于数据库切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好久没有使用原生的 jdbc 来连接数据库了,之前一直使用ssh框架,感觉手生了好多,唉,不复习真的什么都忘了。

首先要准备连接的四个必须的字符串,分别是 jdbcUrl、driverClass、user、pasword,我习惯在类路径下建一个db.properties 文件来保存这四个字符串,在连接时从这个properties 文件中读取,这样使用配置的方式可以轻松的切换到其他的数据库,比如 oracle之类的。

db.properties 文件内容如下:

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test
user=root
password=340818
然后在 getConnection 方法中,先使用流的方式读取类路径下这个 properties 文件,将连数据库的条件装配上,代码如下:

// 读取类路径下的 jdbc.properties 文件
		InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream(
				"jdbc.properties");
		Properties properties = new Properties();
		properties.load(in);

		driverClass = properties.getProperty("driver");
		jdbcUrl = properties.getProperty("jdbcUrl");
		user = properties.getProperty("user");
		password = properties.getProperty("password");
后面就是正常的连接数据库代码了:

		Driver driver = (Driver) Class.forName(driverClass).newInstance();
		Properties info = new Properties();
		info.put("user", user);
		info.put("password", password);
		Connection connection = driver.connect(jdbcUrl, info);




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值