如何使用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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短