JDBC数据库驱动的使用
1、下载数据库驱动(使用的是MYSQL数据库)
https://www.mysql.com/products/connector/
2、导入到项目文件
导入:JRE System Library ------>Build Path ------> Configure Build Path
------> Add External JARs ------> 添加下载好的jar驱动文件 ------>Apply and Close
3、使用数据库驱动连接数据库
加载数据库驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("加载数据库驱动失败!");
e.printStackTrace();
}
获取数据库连接
try {
con = DriverManager.getConnection(url, user, password);
if(con !=null) {
System.out.println("数据库连接成功!");
}
} catch (SQLException e) {
System.out.println("数据库连接失败!");
e.printStackTrace();
}
结果:
注:示例使用的版本为 mysql-connector-java-5.1.39-bin ,其他高版本有一些不同
高版本示例:mysql-connector-java-8.0.12
驱动类名:Class.forName("com.mysql.cj.jdbc.Driver");
url: "jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8&useSSL=false"