日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

jdbc preparestatement 执行多条语句_第二十一天JDBC编程

發布時間:2024/9/3 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 jdbc preparestatement 执行多条语句_第二十一天JDBC编程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

JDBC編程

JDBC是連接數據庫和Java程序的橋梁,通過JDBC API可以方便地實現對各種主流數據庫的操作。本篇將介紹一下如何使用JDBC操作數據庫(以MySQL為例)。

一、JDBC

JDBC制定了統一訪問各類關系數據庫的標準接口,為各個數據庫廠商提供了標準接口的實現。

JDBC規范將驅動程序歸結為以下幾類(選自Core Java Volume Ⅱ——Advanced Features):

  • 第一類驅動程序將JDBC翻譯成ODBC,然后使用一個ODBC驅動程序與數據庫進行通信。
  • 第二類驅動程序是由部分Java程序和部分本地代碼組成的,用于與數據庫的客戶端API進行通信。
  • 第三類驅動程序是純Java客戶端類庫,它使用一種與具體數據庫無關的協議將數據庫請求發送給服務器構件,然后該構件再將數據庫請求翻譯成數據庫相關的協議。
  • 第四類驅動程序是純Java類庫,它將JDBC請求直接翻譯成數據庫相關的協議。

二、通過JDBC操作數據庫

我們需要訪問數據庫時,首先要加載數據庫驅動,只需加載一次,然后在每次訪問數據庫時創建一個Connection實例,獲取數據庫連接,獲取連接后,執行需要的SQL語句,最后完成數據庫操作時釋放與數據庫間的連接。

1. 加載數據庫驅動

Java加載數據庫驅動的方法是調用Class類的靜態方法forName(),語法格式如下:

Class

例如加載MySQL數據庫驅動如下:

try

如果加載成功,會將加載的驅動類注冊給DriverManager;如果加載失敗,會拋出ClassNotFoundException異常。

需要注意的是,要在項目中導入mysq-connection-java的jar包,方法是在項目中建立lib目錄,在其下放入jar包。

右鍵jar包 Build Path->Add to Build Path。

之后會多出一個Referenced Libraries,導入成功。

2. 建立連接

加載完數據庫驅動后,就可以建立數據庫的連接了,需要使用DriverManager類的靜態方法getConnection()方法來實現。如下:

Class

url是數據庫的url,其中mysql指定數據庫為mysql數據庫,localhost是本地計算機,可以換成IP地址127.0.0.1,3306為MySQL數據庫的默認端口號,database_name是所要連接的數據庫名;user和password對應數據庫的用戶名和密碼;最后再通過getConnection建立連接。

3. 對數據庫表中數據進行增刪改查

建立了連接之后,就可以使用Connection接口的createStatement()方法來獲取Statement對象,也可以調用prepareStatement()方法獲得PrepareStatement對象,通過executeUpdate()方法來執行SQL語句。

先看一個查詢的。

1

運行結果如下:

一般在數據庫中我們將性別寫為數字,然后用Java語言進行轉換,比如上述運行結果,1代表男性、2代表女性、0代表未知,我們修改sex = rs.getInt("sex");這行代碼如下:

sex

首先在while循環的外面加上String _sex,在輸出中將sex改為_sex即可,運行結果如下:

對于插入,我們可以使用Statement接口中的executeUpdate()方法,如下:

String

還可以使用PreparedStatement接口中的executeUpdate()方法,如下:

String

修改同插入,也有上述兩種方法,只需更改sql語句即可。

刪除也是一個很常用的操作,使用executeUpdate()方法執行用來做刪除的SQL語句,方法同上方Statement接口的操作。

三、完整實例

下面給一個完整的例子,該例子的數據庫配置文件在外部的properties中,該例子以SQL Server為例,其它的數據庫都是同樣的道理。

1. jdbc.properties

用于編寫數據庫配置文件,不直接寫在程序中的好處是提高了靈活性,如果需要修改數據庫名稱或配置等信息,可以在這里修改,無需改動程序。

1

2. DBUtils.java

編寫JDBC代碼。

1 import java.io.*;2 import java.sql.Connection;3 import java.sql.DriverManager;4 import java.sql.PreparedStatement;5 import java.sql.ResultSet;6 import java.sql.SQLException;7 import java.sql.Statement;8 import java.util.Properties;9 10 public class DBUtil {11 private final String dbConnFile = "resource/database/jdbc.properties";12 private Connection conn=null;13 private String dbDriver; //定義驅動 14 private String dbURL; //定義URL 15 private String userName; //定義用戶名 16 private String password; //定義密碼 17 18 //從配置文件取數據庫鏈接參數 19 private void loadConnProperties(){ 20 Properties props = new Properties(); 21 try { 22 props.load(new FileInputStream(dbConnFile));//根據配置文件路徑Conf加載配置文件 23 } catch (FileNotFoundException e) { 24 e.printStackTrace(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 this.dbDriver = props.getProperty("driver");//從配置文件中取得相應的參數并設置類變量 29 this.dbURL = props.getProperty("url"); 30 this.userName = props.getProperty("username"); 31 this.password = props.getProperty("password"); 32 33 }34 35 public boolean openConnection(){36 try { 37 loadConnProperties();38 Class.forName(dbDriver); 39 this.conn = DriverManager.getConnection(dbURL,userName,password);40 return true;41 } catch(ClassNotFoundException classnotfoundexception) { 42 classnotfoundexception.printStackTrace(); 43 System.err.println("db: " + classnotfoundexception.getMessage()); 44 } catch(SQLException sqlexception) { 45 System.err.println("db.getconn(): " + sqlexception.getMessage()); 46 }47 return false;48 }49 50 51 protected void finalize() throws Exception{52 try {53 if(null!=conn)54 conn.close();55 }catch (SQLException e) {56 e.printStackTrace();57 }58 59 }60 61 // 查詢并得到結果集62 public ResultSet execQuery(String sql) throws Exception {63 ResultSet rstSet = null;64 try {65 if (null == conn)66 throw new Exception("Database not connected!");67 Statement stmt = conn.createStatement();68 rstSet = stmt.executeQuery(sql);69 } catch (SQLException e) {70 e.printStackTrace();71 }72 return rstSet;73 }74 75 // 插入一條新紀錄,并獲取標識列的值76 public ResultSet getInsertObjectIDs(String insertSql) throws Exception{77 ResultSet rst = null;78 try {79 if(null==conn)80 throw new Exception("Database not connected!");81 82 Statement stmt = conn.createStatement();83 84 stmt.executeUpdate(insertSql, Statement.RETURN_GENERATED_KEYS);85 rst = stmt.getGeneratedKeys();86 87 } catch (SQLException e) {88 e.printStackTrace();89 }90 return rst;91 }92 93 //以參數SQL模式插入新紀錄,并獲取標識列的值94 public ResultSet getInsertObjectIDs(String insertSql, Object[] params) throws Exception {95 ResultSet rst = null;96 PreparedStatement pstmt = null ;97 try {98 if (null == conn)99 throw new Exception("Database not connected!"); 100 pstmt = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); 101 102 if(null != params){ 103 for (int i = 0; i < params.length; i++) { 104 pstmt.setObject(i + 1, params[i]); 105 } 106 } 107 pstmt.executeUpdate(); 108 rst = pstmt.getGeneratedKeys(); 109 } catch (SQLException e) { 110 e.printStackTrace(); 111 } 112 return rst; 113 } 114 115 116 117 // 插入、更新、刪除 118 public int execCommand(String sql) throws Exception{ 119 int flag = 0; 120 try { 121 if(null==conn) 122 throw new Exception("Database not connected!"); 123 124 Statement stmt = conn.createStatement(); 125 flag = stmt.executeUpdate(sql); 126 127 stmt.close(); 128 } catch (SQLException e) { 129 e.printStackTrace(); 130 } 131 return flag; 132 } 133 134 /* // 存儲過程調用 135 public void callStordProc(String sql, Object[] inParams, SqlParameter[] outParams) throws Exception { 136 CallableStatement cst = null ; 137 try { 138 if (null == conn) 139 throw new Exception("Database not connected!"); 140 cst = conn.prepareCall(sql); 141 142 if(null != inParams){ 143 for (int i = 0; i < inParams.length; i++) { 144 cst.setObject(i + 1, inParams[i]); 145 } 146 } 147 148 if (null!=outParams){ 149 for (int i = 0; i < inParams.length; i++) { 150 cst.registerOutParameter(outParams[i].getName(), outParams[i].getType()); 151 } 152 } 153 cst.execute(); 154 } catch (SQLException e) { 155 e.printStackTrace(); 156 } 157 } 158 */ 159 // 釋放資源 160 public void close(ResultSet rst) throws Exception { 161 try { 162 Statement stmt = rst.getStatement(); 163 rst.close(); 164 stmt.close(); 165 } catch (SQLException e) { 166 e.printStackTrace(); 167 } 168 } 169 170 public PreparedStatement execPrepared(String psql) throws Exception { 171 PreparedStatement pstmt = null ; 172 try { 173 if (null == conn) 174 throw new Exception("Database not connected!"); 175 pstmt = conn.prepareStatement(psql); 176 } catch (SQLException e) { 177 e.printStackTrace(); 178 } 179 return pstmt; 180 } 181 182 183 // 釋放資源 184 public void close(Statement stmt) throws Exception { 185 try { 186 stmt.close(); 187 } catch (SQLException e) { 188 e.printStackTrace(); 189 } 190 } 191 192 // 釋放資源 193 public void close() throws SQLException, Exception{ 194 if(null!=conn){ 195 conn.close(); 196 conn=null; 197 } 198 } 199 200 public Connection getConn() { 201 return conn; 202 } 203 204 205 public static void main(String[] args) { 206 207 } 208 }

3. DBUtil_TestDriver.java

測試程序。

1

總結

以上是生活随笔為你收集整理的jdbc preparestatement 执行多条语句_第二十一天JDBC编程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。