如何使用JDBC中的属性文件与数据库建立连接?
DriverManager 类的getConnection()方法的变体之一接受数据库的url(字符串格式)一个属性文件并建立与数据库的连接。
Connection con = DriverManager.getConnection(url, properties);
使用此方法与数据库建立连接-
将驱动程序类名称设置为系统属性-
System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");创建一个属性对象为-
Properties properties = new Properties();
将用户名和密码添加为上述创建的Properties对象,如下所示:
properties.put("user", "root");
properties.put("password", "password");最后,通过传递URL和properties对象作为参数来调用DriverManager 类的getConnection() 方法。
//获得连接 String url = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(url, properties);
以下JDBC程序使用属性文件建立与MYSQL数据库的连接。
示例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class EstablishingConnectionUsingProperties {
public static void main(String args[]) throws SQLException {
//注册驱动程序
System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");
Properties properties = new Properties();
properties.put("user", "root");
properties.put("password", "password");
//获得连接
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, properties);
System.out.println("Connection established: "+ con);
}
}输出结果
Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下