本文使用的 Java 集成环境是 eclipse,数据库是 MySQL 8.0 以上的版本,本文使用手动获取数据库连接的方式实现连接
目录
首先我们要导入对应的第三方 API jar 包,可以从本人百度网盘中直接获取
链接:https://pan.baidu.com/s/1vgneasvM0TD4ZJwOgL8P-w
提取码:ah6u

导入之后一定要 Build Path,产生上图中 Referenced Libraries 的 jar 包,一定要进行 Build Path,否则无法使用 API

建立 properties 文件是为了存储数据库的基本信息
jdbc:mysql协议
localhost:ip地址
3306:默认mysql的端口号
test:test数据库
- user=root
- password=password
- url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
- driverClass=com.mysql.jdbc.Driver
为什么 url 要加 ?后面的·一长串呢,是因为不加会有报错的风险(Unknown initial character set index '255' received from server. Initial client character set can be forced via the 'characterEncoding' property. )
- import java.io.InputStream;
- import java.sql.Driver;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
- import com.mysql.jdbc.Connection;
-
- public class JDBCTest {
- public static void main(String[] args) throws Exception {
- //1.读取文件中的信息
- InputStream is = JDBCTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
- Properties pros = new Properties();
- pros.load(is);
- String user = pros.getProperty("user");
- String password = pros.getProperty("password");
- String url = pros.getProperty("url");
- String driverClass = pros.getProperty("driverClass");
-
- //2.加载驱动
- Class.forName(driverClass);
-
- //3.获取连接
- Connection conn = (Connection) DriverManager.getConnection(url, user, password);
- System.out.println(conn);
- }
- }
1. 实现了数据与代码的分离,实现了解耦
2. 如果需要修改配置文件信息,可以避免程序重新打包