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