加載JDBC驅動
try {
// Load the JDBC driver 加載指定名稱的類
String driverName = "org.gjt.mm.mysql.Driver";
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// Could not find the driver
}
列出加載的全部JDBC驅動名稱
List drivers = Collections.list(DriverManager.getDrivers());
for (int i=0; i<drivers.size(); i++) {
Driver driver = (Driver)drivers.get(i);
// Get name of driver 驅動名稱
String name = driver.getClass().getName();
// Get version info 驅動程式的版本資訊
int majorVersion = driver.getMajorVersion();
int minorVersion = driver.getMinorVersion();
boolean isJdbcCompliant = driver.jdbcCompliant();
}
連接配接Oracle 資料庫
Connection connection = null; try { // Load the JDBC driver String driverName = "oracle.jdbc.driver.OracleDriver"; Class.forName(driverName); // Create a connection to the database String serverName = "127.0.0.1"; String portNumber = "1521"; String sid = "mydatabase"; String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid; String username = "username"; String password = "password"; connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // Could not find the database driver } catch (SQLException e) { // Could not connect to the database }
連接配接MYSQL 資料庫
mysql> GRANT ALL PRIVILEGES ON *.* TO [email protected] IDENTIFIED BY 'password' WITH GRANT OPTION; Connection connection = null; try { // Load the JDBC driver String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver Class.forName(driverName); // Create a connection to the database String serverName = "localhost"; String mydatabase = "mydatabase"; String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url String username = "username"; String password = "password"; connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // Could not find the database driver } catch (SQLException e) { // Could not connect to the database }
連接配接SQL2000資料庫
Connection connection = null; try { String driverName = "com.jnetdirect.jsql.JSQLDriver"; // NetDirect JDBC driver String serverName = "127.0.0.1"; String portNumber = "1433"; String mydatabase = serverName + ":" + portNumber; String url = "jdbc:JSQLConnect://" + mydatabase; // a JDBC url String username = "username"; String password = "password"; // Load the JDBC driver Class.forName(driverName); // Create a connection to the database connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // Could not find the database driver } catch (SQLException e) { // Could not connect to the database }
直接連接配接ODBC資料源,不用再注冊ODBC資料源
private void getConnect(){ try{ URL url=this.getClass().getResource("../DataBase/"+DBname.toString()); String uri = new String(url.toString()); String sql_url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+uri.substring(6); connect = DriverManager.getConnection(sql_url); statem = connect.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); // 建立資料庫操作類的執行個體,該管理器對該資料庫享有修改的權限 }catch(SQLException er){//捕獲錯誤 :: SQL錯誤 System.out.println("Driver can not get connection"+er.getMessage()); System.exit(0);//軟體正常退出 }//end_catch(); }
列出全部建立的可以使用資料庫連接配接接口
try {
// Load the driver
String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
// Get the Driver instance 擷取驅動的執行個體類
String url = "jdbc:mysql://a/b";
Driver driver = DriverManager.getDriver(url);
// Get available properties 擷取可以使用的屬性
DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
for (int i=0; i<info.length; i++) {
// Get name of property
String name = info[i].name;
// Is property value required?
boolean isRequired = info[i].required;
// Get current value
String value = info[i].value;
// Get description of property
String desc = info[i].description;
// Get possible choices for property; if null, value can be any string
String[] choices = info[i].choices;
}
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
}
Here's the property values for the MySql driver:
Name(isRequired): Description
default: default value
choices: ...
HOST(true): Hostname of MySQL Server
default: a
PORT(false): Port number of MySQL Server
default: 3306
DBNAME(false): Database name
default: b
user(true): Username to authenticate as
default: null
password(true): Password to use for authentication
default: null
autoReconnect(false): Should the driver try to re-establish bad connections?
default: false
choices: true, false
maxReconnects(false): Maximum number of reconnects to attempt if autoReconnect is true
default: 3
initialTimeout(false): Initial timeout (seconds) to wait between failed connections
default: 2
查詢資料庫是否支援存儲過程
try { DatabaseMetaData dmd = connection.getMetaData(); if (dmd.supportsTransactions()) { // Transactions are supported } else { // Transactions are not supported } } catch (SQLException e) { }
假如發生操作時據庫的錯誤,本次操作復原,取消本次的全部操作
try {
// Disable auto commit 設定送出的為手動送出資料操作動作
connection.setAutoCommit(false);
// Do SQL updates...
// Commit updates 送出資料庫操作
connection.commit();
connection.setAutoCommit(true);
} catch (SQLException e) {
// Rollback update 取消本次全部的資料庫操作
connection.rollback();
}
操作處理SQL Exception
try { // Execute SQL statements... 操作SQL的語句 } catch (SQLException e) { while (e != null) { // Retrieve a human-readable message identifying the reason for the exception String message = e.getMessage(); // This vendor-independent string contains a code that identifies // the reason for the exception. // The code follows the Open Group SQL conventions. String sqlState = e.getSQLState(); // Retrieve a vendor-specific code identifying the reason for the exception. int errorCode = e.getErrorCode(); // If it is necessary to execute code based on this error code, // you should ensure that the expected driver is being // used before using the error code. // Get driver name String driverName = connection.getMetaData().getDriverName(); if (driverName.equals("Oracle JDBC Driver") && errorCode == 123) { // Process error... } // The exception may have been chained; process the next chained exception e = e.getNextException(); } }
查詢是否有SQL Warning 發生
try { // Get warnings on Connection object SQLWarning warning = connection.getWarnings(); while (warning != null) { // Process connection warning String message = warning.getMessage(); String sqlState = warning.getSQLState(); int errorCode = warning.getErrorCode(); warning = warning.getNextWarning(); } // Create a statement Statement stmt = connection.createStatement(); // Use the statement... // Get warnings on Statement object warning = stmt.getWarnings(); if (warning != null) { // Process statement warnings... } // Get a result set ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table"); while (resultSet.next()) { // Use result set // Get warnings on the current row of the ResultSet object warning = resultSet.getWarnings(); if (warning != null) { // Process result set warnings... } } } catch (SQLException e) { }
擷取資料庫驅動的連接配接
try {
DatabaseMetaData dmd = connection.getMetaData();
String driverName = dmd.getDriverName(); // Mark Matthew's MySQL Driver
} catch (SQLException e) {
}
//The best you can do is to use the URL used to create the connection: 最好的方法
try {
// Create connection from URL
Connection conn = DriverManager.getConnection(url, username, password);
// Get driver from URL
Driver driver = DriverManager.getDriver(url);
} catch (SQLException e) {
}
設定SQL操作傳回的影響的行數
try { // Get the fetch size of a statement Statement stmt = connection.createStatement (); int fetchSize = stmt.getFetchSize(); // Set the fetch size on the statement 設定傳回的行數 stmt.setFetchSize(100); // Create a result set 建立一個結果集 ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table"); // Change the fetch size on the result set 指定結果集的容量 resultSet.setFetchSize(100); } catch (SQLException e) { }