//加載驅動Class.forName(driverClass); //加載MySQL的驅動Class.forName("com.mysql.jdbc.Driver");
- //加載Oracle的驅動
- Class.forName("oracle.jdbc.driver.OracleDriver");
//獲取數據庫鏈接DriverManager.getConnection(String url, String user, String password); //MySQL數據庫URL的寫法jdbc:mysql://hostname:port/databasename //Oracle數據庫URL的寫法jdbc:oracle:thin:@hostname:port:databasename
package com.sqq.mystudy.JDBC;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class JDBCTest { public static void main(String[] args) { try { //一、加載MySQL數據庫驅動 Class.forName("com.mysql.jdbc.Driver"); //二、使用DriverManager獲取數據庫鏈接 Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mytest", "root","pwd" ); //三、使用Connection建立一個Statement對象 Statement stmt = conn.createStatement(); //四、執行SQL語句 ResultSet rs = stmt.executeQuery("SELECT * FROM mtest"); while (rs.next()) { System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t\t" + rs.getString(3)); }
rs.close();
stmt.close();
conn.close();
} catch (Exception e) { System.out.println(e); } }}
SET AUTOCOMMIT = {0 | 1} #0爲關閉自動提交,即開啓事務
//關閉自動提交,開啓事務conn.setAutoCommit(false);
//提交事務conn.commit();
//回滾事務conn.rollback();
public static void commitTransaction(String[] sqls) { //加載驅動 try { Class.forName(dbPar.getDriver()); Connection conn = null; try { conn = DriverManager.getConnection(dbPar.getUrl(), dbPar.getUser(), dbPar.getPassword()); //關閉自動提交事務 conn.setAutoCommit(false); Statement stmt = conn.createStatement(); for (String sql : sqls) { System.out.println(sql); } //提交事務 conn.commit(); //關閉鏈接 conn.close(); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } }