天天看點

java連接配接資料庫的方式_Java連接配接資料庫的方法

一、直接使用Driver類

public void testDriver(){

//1.建立一個Driver 實作類的對象

Driver driver=new com.mysql.jdbc.Driver();

//2.準備連接配接資料庫的基本資訊:url,user,password

String url="jdbc:mysql://localhost:3306/test";

Properties info = new Properties();

info.put("user", "root");

info.put("password","1230");

//3.調用Driver 接口的 connection(url,info)擷取資料庫連接配接

Connection conn=driver.connect(url, info);

System.out.println(conn);

}

二、通過檔案連接配接資料庫

public Connection getConnection() throws Exception{

String driverClass = null;

String jdbcUrl = null;

String user = null;

String password = null;

//讀取類路徑下的jdbc,properties檔案

InputStream in=

getClass().getClassLoader().getResourceAsStream("jdbc.properties");

Properties properties=new Properties();

properties.load(in);

driverClass = properties.getProperty("driver");

jdbcUrl = properties.getProperty("jabcUrl");

user = properties.getProperty("user");

password = properties.getProperty("password");

//通過反射常見 Driver對象

Driver driver=

(Driver)Class.forName(driverClass).newInstance();

Properties info = new Properties();

info.put("user", user);

info.put("password", password);

//通過Driverd 的 connect 方法擷取資料庫連接配接

Connection conn = driver.connect(jdbcUrl, info);

return conn;

}

三、通過DriverManager連接配接資料庫

public static void testDriverManager() throws Exception {

//1,準備連接配接資料庫的4個字元串:驅動全類名、JDBC URL、user、password

String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

String jdbcUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=Ywpw";

String user="zyj";

String password="zyj";

//2.加載資料庫驅動程式(注冊驅動)

Class.forName(driverClass);

Connection conn=

DriverManager.getConnection(jdbcUrl, user, password);

System.out.println(conn);

}

四、連接配接各資料庫的JDBCUrl

Mysql:jdbc:mysql://localhost:3306/資料庫名

SQLServer:jdbc:sqlserver://localhost:1433;DatabaseName=資料庫名

Oracle:jdbc:oracle:thin:@localhost:1521:orcl