JDBC_通过DriverManager获得数据库连接
生活随笔
收集整理的這篇文章主要介紹了
JDBC_通过DriverManager获得数据库连接
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package day_18;import org.junit.Test;import java.io.InputStream;
import java.sql.*;
import java.sql.DriverManager;
import java.util.Properties;
/*CTRL+右擊 在某個類名或者方法上即可打開其對應的API文檔!*/
/** DriverManager 是驅動的管理類,比直接使用driver更加方便* my.sql.Driver 應用程序不再需要使用Class.forName()顯式加載JDBC驅動程序。* 目前使用加載JDBC驅動程序的現有程序Class.forName(driverClass)將不執行任何工作。* 當調用方法getConnection時,* DriverManager將嘗試從初始化中加載的驅動程序中找到合適的驅動程序,* 并使用與當前小程序或應用程序相同的類加載器顯式加載驅動程序。* 代碼,一步到位:* Connection connection=DriverManager.getConnection(jdbcUrl,user,password);**/
public class testDriverManager {@Testpublic void test1() throws Exception{//1.準備數據庫的連接的4個字符串String driverClass=null,jdbcUrl=null,user=null,password=null;//jdbc:mysql:///books ;也可以將localhost省略掉!//2.讀取類路徑下的jdbc.properties 文件InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");Properties properties =new Properties();properties.load(in);driverClass =properties.getProperty("driver");jdbcUrl=properties.getProperty("jdbcUrl");user = properties.getProperty("user");password = properties.getProperty("password");//3.加載數據庫驅動程序(注冊驅動),driver對應的實現類中有注冊驅動的靜態代碼塊// Class.forName(driverClass); ////或這么手動加載,也可以注冊多個數據庫連接的代碼塊//DriverManager.registerDriver( Class.forName(driverClass).newInstance());//4.通過DriverManager 的getConnection()方法獲取數據庫連接。Connection connection=DriverManager.getConnection(jdbcUrl,user,password);System.out.print(connection); //com.mysql.jdbc.JDBC4Connection@19e1023e
}
}
?
轉載于:https://www.cnblogs.com/zhazhaacmer/p/9959602.html
總結
以上是生活随笔為你收集整理的JDBC_通过DriverManager获得数据库连接的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [2018/11/14]思考
- 下一篇: 教你用webpack搭一个vue脚手架[