获取数据库连接的五种方式
方式一
要素1.Driver(驱动)接口实现类
Driver driver =new com.mysql,jdbc,Driver();
要素2.URL
String url="jdbc.mysql://localhost:3306/db1";
public void testConnection1() throws SQLEeception{
Driver driver =new com.mysql,jdbc,Driver();
String url="jdbc.mysql://localhost:3306/db1";;
Properties info = new Properties();
Connection conn = driver.connect(url,info)
System.out.println(conn)
}
方式二:对方式一的迭代:再如下的程序当中不出现第三方的api,使得程序具有更好的可移植性
Class aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)aClass.newInstance();
String url="jdbc:mysql://localhost:3306/db1?useSSL=false";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","lijiaxiang123.");
Connection conn = driver.connect(url, info);
System.out.println(conn);
方式三:使用DriverManager替换Driver
Class aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)aClass.newInstance();
String url="jdbc:mysql://localhost:3306/db1?useSSL=false";
String user="root";
String password="lijiaxiang123.";
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
方式四:可以只是加载驱动,不用显示的注册驱动了
String url="jdbc:mysql://localhost:3306/db1?useSSL=false";
String user="root";
String password="lijiaxiang123.";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
方式五:将数据库连接需要的四个基本信息声明在配置文件当中,通过图区配置文件的方式,获取连接
配置文件:
user=root
password=lijiaxiang123.
url=jdbc:mysql://localhost:3306/db1?useSSL=false
driverClass=com.mysql.jdbc.Driver
程序:
InputStream is = ConnectionTest.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");
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
|