JDBCDriver介面連線資料庫,實際開發基本不用

行走的菠蘿發表於2018-11-02
import java.sql.Connection;
import java.util.Properties;
import com.mysql.jdbc.Driver;
public class JDBCDriver_getConnection {
//通過Driver介面獲取連線,實際開發基本不用
public static void main(String[] args) throws Exception {
new JDBCDriver_getConnection().getConnection(); 
}
public Connection getConnection() throws Exception{
//連線引數
String driverClass = null;
String url=null;
String user = null;
String password = null;
Properties properties = new Properties();//使用Properties
properties.load(getClass().getClassLoader().getResourceAsStream(“jdbc.properties”));//讀取配置文字
//引數變數賦值
user = properties.getProperty(“user”);
password = properties.getProperty(“password”);
url = properties.getProperty(“url”);
driverClass = properties.getProperty(“driverClass”);
//配置connect()的 Properties
Properties info = new Properties();
info.put(“user”, user);
info.put(“password”, password);
Driver driver = (Driver) Class.forName(driverClass).newInstance();//注入驅動
Connection connection = (Connection) driver.connect(url, info);//獲取連線
return connection;
/*
* 以下是jdbc.properties  配置檔案內容,配置檔案需放在src根目錄下
* driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3307/Test
user = root
password = 3306
*/
}
}


相關文章