JDBC的封裝(上)
JDBC工具類封裝
按照之前的步驟的話,我們可以發現有好多的步驟都是重複操作的,我們沒有必要重複的書寫,爲了省事,我們可以把這些重複使用的部分給封裝起來。
可以封裝的步驟:
1. 數據庫連接對象java.sql.Connection獲取過程
2. 關閉資源
public class JdbcUtil{
private static String url = null;
private static String user = null;
private static String password = null;
//利用static修飾的靜態代碼塊完成文件字段自動讀取和驅動
static{
try {
Properties properties = new Properties();
properties.load(new FileInputStream("./src/db.properties"));
String driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
//驅動加載
Class.forName(driverClass);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
//數據庫連接對象
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//處理數據庫操作對應的資源問題
public static void close(Connection connection) {
close(connection, null, null);
}
public static void close(Connection connection, Statement statement) {
close(connection, statement, null);
}
//close方法
public static void close(Connection connection, Statement statement, ResultSet resultSet){
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
我們db.properties文件在src目錄下,內容
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/lalala?useSSL=true
user=root
password=123456
SQL語句注入問題
之前我們查詢的時候使用的是Statement查詢,但是有一個潛在的問題:比如我們要查詢一個數據,這個數據需要根據它的用戶名和對應的密碼才能正確查到 select * form table where username= ‘xxx’ and password = ‘123456’;正常來說是這樣的,但是我們可以通過一些處理可以將password處理掉:
select * from table where username = ‘xxx’ and password= ‘aaaaaa’ or 1=1 --’
我們輸入(aaaaaa’ or 1=1 – )在sql語句的末尾加上了1=1,這個恆爲真,所以哪怕輸入錯誤的信息,只要有這個1=1,我們還是可以查到全部數據
爲了解決這樣的問題我們可以使用PreparedStatement
PreparedStatement
插入操作(以插入操作爲例,刪除和修改步驟是一樣的,只是sql語句有所不同)
//獲取連接對象
Connection connection = JdbcUtil.getConnection();
//sql語句,?佔位符,可以通過後面重新賦值
String sql = "insert into user(id, userName, password) VALUE (?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//賦值
User user = new User(10, "小明", "123456");
preparedStatement.setObject(1, user.getId());
preparedStatement.setObject(2, user.getUserName());
preparedStatement.setObject(3, user.getPassword());
// 使用PreparedStatement執行SQL語句
int affectedRows = preparedStatement.executeUpdate();
最後的時候別忘記關閉資源 JdbcUtil.close(connection, preparedStatement)