Java基礎面試題(16)----JDBC的理解和程式碼演示PrepareStatement
阿新 • • 發佈:2018-12-13
問題
- 說一下對JDBC的理解
- 程式碼演示連線資料庫
- PrepareStatement和statement的使用
解析
- JDBC指的是 Java database connection Java資料庫連線資料庫管理系統。
- 問題是: 實際的資料庫開放廠商有很多種,每個資料庫操作指令都不一樣,如果開發者直接操作,會有很高的不必要的成本和難度,
- 解決方案是:
為了解決這個問題,Java語言進行統一化的管理,Java語言定義了一個介面,讓資料廠商封裝他們的指令,實現這個介面。而對開發者而言,我們只需要帶入開發廠商的實現,一介面的方式呼叫即可(mysql+mysql驅動+JDBC),實現了統一管理。
2. 寫程式碼實現資料庫連線
資料庫的連線共分為
- 載入驅動
- 獲取連線
- 提供預處理物件
- 執行操作
- 釋放資源 程式碼如下:
import java.sql.*; //裝載需要的資訊的類 class Contant{ public static final String URL ="jdbc:oracle:thin:@127.0.0.1:1521:sid"; public static final String USERNAME="username"; public static final String PASSWORD="password"; } //執行方法的類 public class MyConnection { Connection connection= null; Statement statement=null; ResultSet query=null; public void main(String[] args) throws SQLException { try { //驅動獲取連線 connection = DriverManager.getConnection(Contant.URL, Contant.USERNAME, Contant.PASSWORD); //獲取預處理物件 statement = connection.createStatement(); //執行查詢的SQL語句 query = statement.executeQuery("select * from table"); //遍歷結果輸出到控制檯 while (query.next()){ int i = query.getInt("Filed"); String y=query.getString("name"); System.out.println(i+y); } } catch (SQLException e) { e.printStackTrace(); } finally { //釋放資源從下到大進行 query.close(); statement.close(); connection.close(); } } }
3. PrepareStatement和statement的使用
大多數情況下,我們都不會按照上面的程式碼使用statement。我們會使用PrepareStatement來代替,有一下幾個優點:
- PrepareStatement是預編譯的,執行速度較快
- 程式碼的可讀性和可維護性高 雖然使用PrepareStatement來替代Statement會使得程式碼多幾行,但是這樣的程式碼無論從可讀性還是可維護性都比statement高很多。 程式碼演示:
import java.sql.*;
class Contant{
public static final String URL ="jdbc:oracle:thin:@127.0.0.1:1521:sid";
public static final String USERNAME="username";
public static final String PASSWORD="password";
}
public class MyConnection {
Connection connection= null;
PreparedStatement preparedStatement=null;
ResultSet query=null;
public void main(String[] args) throws SQLException {
try {
//驅動獲取連線
connection = DriverManager.getConnection(Contant.URL, Contant.USERNAME, Contant.PASSWORD);
//SQl語句
String sql = "insert into customers(name,email,birth)" + "values(?,?,?)";
//獲取預處理物件
preparedStatement = connection.prepareStatement(sql);
// 設定name欄位
preparedStatement.setString(1, "ATGUIGU");
// 設定email欄位
preparedStatement.setString(2, " [email protected]");
// 設定birth欄位
preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
// 執行操作
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//釋放資源從下到大進行
query.close();
preparedStatement.close();
connection.close();
}
}
}
使用佔位符進行資料的輸入,可以防止使用者的惡意的SQL語句拼接。
- 安全性高 PrepareStatement可以防止SQL注入攻擊,而Statement卻不能 如果使用與預編譯語句,後面傳入的內同不會和原來的語句發生匹配關係,使用Statement會被客戶端惡意攻擊,資料的洩露的風險。
//如使用statement傳入下面的sql語句
query = statement.executeQuery("select * from user where name='zhangsan' and password='***' ");
/**
* 如果使用者在password的位置輸入的是“or 1=1”,
* 會讓where的條件全部為真,查出所有使用者的資訊,導致使用者資訊洩露。
* 如果輸入的是“;drop table user;" 將會有刪除資料庫的風險
*/
所以在我們通常使用的是PrepareStatement進行預處理執行。