代碼展示(重點看注釋)import java.sql.Connection;import java.sql.DriverManager;import java.sql.PReparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class TestJDBC { public static void main(String[] args) { // 數據庫連接 Connection connection = null; // 預編譯的Statement(操作數據庫), // PreparedStatement預編譯的,相同的sql語句,只編譯一次,存到緩存中,下次訪問如果sql語句相同,直接調用緩存,提高數據庫性能 PreparedStatement preparedStatement = null; // 結果集對象 ResultSet resultSet = null; try { // 加載數據庫驅動 Class.forName("com.mysql.jdbc.Driver"); // 通過驅動管理類獲取數據庫鏈接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8","root",null); // 定義sql語句 ?表示占位符 String sql = "select * from user where username = ?"; // 獲取預處理statement preparedStatement = connection.prepareStatement(sql); // 設置參數,第一個參數為sql語句中參數的序號(從1開始),第二個參數為設置的參數值 preparedStatement.setString(1, "王五"); // 向數據庫發出sql執行查詢,查詢出結果集 resultSet = preparedStatement.executeQuery(); // 添加、修改、刪除執行 preparedStatement.executeUpdate(); // 遍歷查詢結果集 while (resultSet.next()) { System.out.println(resultSet.getString("id") + " " + resultSet.getString("username")); } } catch (Exception e) { e.printStackTrace(); } finally { // 釋放資源(倒著釋放:結果集->預處理對象->數據庫連接) if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }}步驟說明1.加載數據庫驅動2.創建并獲取數據庫鏈接3.創建jdbc statement對象4.設置sql語句5.設置sql語句中的參數(使用preparedStatement)6.通過statement執行sql并獲取結果7.對sql執行結果進行解析處理8.釋放資源(resultSet、preparedstatement、connection)問題分析1.數據庫鏈接創建、釋放頻繁造成系統資源浪費從而影響系統性能,如果使用數據庫鏈接池可解決此問題。2.硬編碼部分過多,不易維護,Sql語句、占位符、參數等等。
新聞熱點
疑難解答