動力節點筆記java
- import java.sql.*;
- //採用PreparedStatement根據條件查詢
- public class QueryTest05 {
- public static void main(String[] args) {
- if (args.length == 0) {
- throw new IllegalArgumentException("參數非法,正確使用爲: Java QueryTest05 + 參數");
- }
- Connection conn = null;
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try {
- //第一步,加載數據庫驅動,不一樣的數據庫驅動程序不同
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //第二部,獲得數據庫鏈接
- String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@192.168.21.1:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
- String userName = "system";
- String password = "wanwan";
- conn = DriverManager.getConnection(dburl, userName, password);
- //System.out.println(conn);
- //第三步,獲得PreparedStatement,執行sql
- //採用PreparedStatement不建議採用拼串的方式
- //由於拼串每次的SQL語句不同,這樣就沒有利用PreparedStatement的優勢
- //仍然每次都編譯,和Statement沒什麼差異
- //String sql = "select * from tb_student where sex like '" + args[0] + "'";
- //pstmt = conn.prepareStatement(sql);
- //建議採用佔位符的方式
- //這樣每次SQL語句是同樣的,數據庫就不會再編譯
- //這樣就利用了PreparedStatement的優勢,顯著地提升性能
- //瞭解Statement和PreparedStatement的區別
- String sql = "select * from tb_student where sex like ?";
- pstmt = conn.prepareStatement(sql);
- //注意:此處不要加單引號
- pstmt.setString(1, args[0]);
- //第四部,取得結果集
- //將條件作爲sql語句的一部分進行拼接
- //注意字符串必須採用單引號引發來
- rs = pstmt.executeQuery();
- //System.out.println("sql" + sql);
- while (rs.next()) {
- int id = rs.getInt("id");
- String name = rs.getString("name");
- System.out.println(id + " , " + name);
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- //注意關閉原則:從裏到外
- try {
- if (rs != null) {
- rs.close();
- }
- if (pstmt != null) {
- pstmt.close();
- }
- if (conn != null) {
- conn.close();
- }
- } catch(SQLException e) {
- }
- }
- }
- }