java JDBC

數據庫URL

JDBC URL的通常語法爲: jdbc:subprotocol:other stufffhtml

其中,suprotocol 用於選擇鏈接到數據庫的具體驅動程序,  other stuff 參數的格式隨所使用的subprotocol的不一樣而不一樣java

例如:mysql

jdbc:derby://localhost:1527//COREJAVA;ctreate=truesql

jdbc:postgresql:COREJAVA      // postgresql 和derby是數據庫數據庫

 

驅動程序JAR文件:

驅動文件能夠在數據庫的官網下載;例如mysql的驅動程序下載地址安全

也能夠建立MAVEN項目maven

在:https://dev.mysql.com/downloads/connector/  選擇對應壓縮包下載ide

命令行鏈接:https://www.cnblogs.com/jiangfeilong/p/10587376.htmlpost

maven  JDBC鏈接實例ui

package org.feilong.mysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; //import com.mysql.cj.jdbc.*;

public class Url { public static final String URL = "jdbc:mysql://192.168.1.104:3306/gc"; public static final String USER = "root"; public static final String PASSWORD = "1"; public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("register success"); } catch (ClassNotFoundException e1) { System.out.println("register fail"); e1.printStackTrace(); }//註冊驅動
            
            try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)){//鏈接
            Statement stmt = conn.createStatement();  //執行者
            ResultSet rs = stmt.executeQuery("SELECT * FROM books"); //結果集, //
                while (rs.next()) { System.out.println(rs.getString("author") + " "+rs.getString(2)); } conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } } }
public ResultSet executeQuery()執行select語句 返回結果在result裏
public int executeUpdate()
public long executelargeUpdate()
執行Insert/update/delete/create table/drop table等 返回修改的行數

public boolean execute() 執行任何語句

ReultSet使用注意事項:

獲得數據庫信息

try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)){//鏈接
            Statement stmt = conn.createStatement();  //執行者 //Integer rs = stmt.executeUpdate("DROP DATABASE IF EXISTS mysql_test1"); 
            DatabaseMetaData meta = conn.getMetaData(); ResultSet rs1 = meta.getCatalogs(); while(rs1.next()) System.out.println(rs1.getString(1)); conn.close();

事務處理

JDBC 事務步驟

關閉自動提交,實現多語句同一事務

 connection.setAutoCommit(false);

connection.commit();提交事務

connection.rollback();回滾事務

保存點機制

  connection.setSavepoint()

  connection.rollback(savepoint)

public static void execute(Connection conn,String sql){ try { Statement stmt = conn.createStatement(); boolean rs = stmt.execute(sql); } catch (SQLException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } } public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("register success"); } catch (ClassNotFoundException e1) { System.out.println("register fail"); e1.printStackTrace(); }//註冊驅動
            
            try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)){//鏈接
                conn.setAutoCommit(false); //關閉自動提交
 execute(conn,"USE mysql_test"); // PreparedStatement pstmt = conn.prepareStatement(sql); //pstmt.setString(1,"cust_id INT NOT NULL AUTO_INCREMENT,");
 String sql = "CREATE TABLE customers ( ?,?,?,?,?,?)"; execute(conn,"CREATE TABLE customers" + 
                    "(" + 
                    "cust_id INT NOT NULL AUTO_INCREMENT, " + //#INCREMENT 能夠爲表中的數據類型爲整形的列設置自增型 
                    "cust_name CHAR(50) NOT NULL,        "  + //#不容許null值的列 
                    "cust_set CHAR(1) NOT NULL DEFAULT 0, " + //不容許null值的列且默認值是0 
                    "cust_address CHAR(50) NULL," + 
                    "cust_contact CHAR(50) NULL," + 
                    "PRIMARY KEY(cust_id)  " +    //設置cust_id 爲主鍵 
                    ")"); Savepoint phase1 = conn.setSavepoint(); //設置一個保存點
                    execute(conn,"SHOW TABLES"); conn.rollback(phase1); //回到保存點 即上面2行無效
                    conn.commit(); //執行操做
                    System.out.println("success"); //DatabaseMetaData meta = conn.getMetaData(); //ResultSet rs1 = meta.getCatalogs(); //while(rs.next()) //System.out.println(rs.getString(1));
 conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block
 e.printStackTrace(); }

 

 安全的字符串拼接PreparedStatement 

普通的字符串拼接可能會被人加入惡意代碼,使用PreparedStatement能夠避免

 PreparedStatement採用待定係數法,使用示例

String sql = "INSERT INTO customers VALUES( ?,?,?,?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1,1);  //替換sql裏的?號
                    pstmt.setString(2, "feilong"); pstmt.setString(3, "1"); pstmt.setString(4, "www.feilong.com"); pstmt.setString(5, "china"); int rs = pstmt.executeUpdate(); Savepoint phase1 = conn.setSavepoint(); //設置一個保存點
                    execute(conn,"SHOW TABLES"); conn.rollback(phase1); //回到保存點 即上面2行無效
                    conn.commit(); //執行操做
                    System.out.println("success");

 PreparedStatement有一個 Batch方法能夠批量提交

try(Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)){//鏈接
                conn.setAutoCommit(false); //關閉自動提交
 execute(conn,"USE mysql_test"); //pstmt.setString(1,"cust_id INT NOT NULL AUTO_INCREMENT,");
 String sql = "INSERT INTO customers VALUES( ?,?,?,?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); for(int i = 2; i < 100; i++){ pstmt.setInt(1,i);  //替換sql裏的?號
                    pstmt.setString(2, "feilong"); pstmt.setString(3, "1"); pstmt.setString(4, "www.feilong.com"); pstmt.setString(5, "china"); pstmt.addBatch(); //添加到batch列表
 } // int rs = pstmt.executeUpdate();
                    pstmt.executeBatch(); //所有提交 //pstmt.close();
                   Savepoint phase1 = conn.setSavepoint(); //設置一個保存點
                   execute(conn,"SHOW TABLES"); conn.rollback(phase1); //回到保存點 即上面2行無效
                   conn.commit(); //執行操做
                    System.out.println("success");

ResultSetMetaData

ResultSet能夠用來承載全部的select語句返回的結果集

ResultSetmetaData用來獲取ResultSet返回的屬性(如,沒一行的名字類型等)

示例:

try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {// 鏈接
            conn.setAutoCommit(false); // 關閉自動提交
            execute(conn, "USE mysql_test"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM customers"); ResultSetMetaData meta = rs.getMetaData(); //獲得元數據 int cols = meta.getColumnCount(); //獲得列的數量 for(int i = 1; i <= cols; i++){ System.out.println(meta.getColumnName(i) + "," + meta.getColumnTypeName(i));; } // pstmt.close();
            Savepoint phase1 = conn.setSavepoint(); // 設置一個保存點
            execute(conn, "SHOW TABLES"); conn.rollback(phase1); // 回到保存點 即上面2行無效
            conn.commit(); // 執行操做
            System.out.println("success"); // DatabaseMetaData meta = conn.getMetaData(); // ResultSet rs1 = meta.getCatalogs(); // while(rs.next()) // System.out.println(rs.getString(1));
            conn.close();

 

數據庫鏈接池

 

享元模式

 

 

 C3P0鏈接池

 

 

 

//C3p0鏈接池
package org.feilong.mysql; import java.sql.Connection; import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0Factory1 { private static ComboPooledDataSource dataSource = null; public static void init() throws Exception{ dataSource = new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.cj.jdbc.Driver"); //加載驅動 dataSource.setJdbcUrl("jdbc:mysql://192.168.1.104:3306/mysql_test"); //數據庫URL dataSource.setUser("root"); //設置賬號 dataSource.setPassword("1"); //設置密碼 dataSource.setMinPoolSize(5); //設置初始鏈接數量 dataSource.setAcquireIncrement(5); //設置每次增長的數量 dataSource.setMaxPoolSize(20); //設置最大鏈接數量 } public static Connection getConnection() throws Exception{ if(dataSource == null){ init(); } return dataSource.getConnection(); //鏈接數據庫 } }

Druid和加載properies鏈接示例

package org.feilong.mysql; import com.alibaba.druid.pool.DruidDataSourceFactory; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; import com.alibaba.druid.pool.DruidDataSource; public class DruidFactory1 { private static DruidDataSource dataSource = null; public static void init() throws Exception { Properties properties = new Properties(); //Properties 配置參數文件
 InputStream in = DruidFactory1.class.getClassLoader().getResourceAsStream("druid.properties"); properties.load(in); dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties); in.close(); } public static Connection getConnection() throws Exception{ if( dataSource == null) { init(); } return dataSource.getConnection(); } }

 

package org.feilong.mysql; import java.sql.*; import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.RowSetFactory; import javax.sql.rowset.RowSetProvider; public class SelectTest { public static void main(String[] args) { Connection conn = null; try { conn = DruidFactory1.getConnection(); Statement stmt = conn.createStatement(); System.out.println("create success"); ResultSet rs = stmt.executeQuery("SELECT * FROM mysql_test.customer ORDER BY cust_address"); while (rs.next()) { System.out.println(rs.getRow()+", " +rs.getString(1) + ", " + rs.getString(2)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

 

properties配置文件

 

driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/test
username=root password=123456 filters=stat initialSize=2 maxActive=300 maxWait=60000 timeBetweenEvictionRunsMillis=60000 minEvictableIdleTimeMillis=300000 validationQuery=SELECT 1 testWhileIdle=true testOnBorrow=false testOnReturn=false poolPreparedStatements=false maxPoolPreparedStatementPerConnectionSize=200
相關文章
相關標籤/搜索