1.MySQL:
package com.text.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/***
* 連接MySql數據庫
*@author <a href="mailto:[email protected]">chenqihao</a>
*@version 2013-3-9
*/
public class JDBCConn {
public Connection getConnection() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/books";
String user = "root";
String password = "123";
Connection conn = null;
try {
Class.forName(driver);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
JDBCConn jdbc = new JDBCConn();
System.out.println(jdbc.getConnection());
}
}
2.SQLServer:
package com.text.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 鏈接SQLServer數據庫內
* @author <a href="mailto:[email protected]">chenqihao</a>
*@version 2013-9-13
*/
public class JDBCConnSqlServer {
public Connection getConnectionSql() {
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databasename=li"; // 1433是數據庫的端口,"li"是你的數據庫名稱
String userName = "sa"; // sa是數據庫的超級用戶,最好不要換別的名字,權限問題
String password = "123456"; // sa的密碼
Connection dbConn = null;
try {
Class.forName(driverName).newInstance();
dbConn = DriverManager.getConnection(dbURL, userName, password);
System.out.println("連接成功!");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (dbConn != null)
dbConn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
JDBCConnSqlServer jdbc = new JDBCConnSqlServer();
System.out.println(jdbc.getConnectionSql());
}
}
3.Oracle:
package com.text.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Oracle鏈接數據庫類
* @author <a href="mailto:[email protected]">chenqihao</a>
*@version 2013-9-13
*/
public class JDBCConnOracle {
public static Connection getConnection() {
// 定義一個連接對象
Connection conn = null;
// 定義連接數據庫的URL資源
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
// 定義連接數據庫的用戶名稱與密碼
String username = "scott";
String password = "tiger";
// 加載數據庫連接驅動
String className = "oracle.jdbc.driver.OracleDriver";
try {
Class.forName(className);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 獲取數據庫的連接對象
try {
conn = DriverManager.getConnection(url, username, password);
System.out.println("數據庫連接建立成功...");
}
catch (SQLException e) {
e.printStackTrace();
}
// 返回連接對象
return conn;
}
public static void main(String[] args) {
JDBCConnOracle jdbc = new JDBCConnOracle();
System.out.println(jdbc.getConnection());
}
}