動力節點筆記java
- import java.sql.*;
- //採用Statement根據條件查詢
- public class QueryTest04 {
- public static void main(String[] args) {
- if (args.length == 0) {
- throw new IllegalArgumentException("參數非法,正確使用爲: Java QueryTest04 + 參數");
- }
- Connection conn = null;
- Statement stmt = 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);
- //第三步,建立Statement,執行SQL語句
- stmt = conn.createStatement();
- //第四部,取得結果集
- //將條件作爲sql語句的一部分進行拼接
- //注意字符串必須採用單引號引發來
- //rs = stmt.executeQuery("select * from tb_student where sex like '" + args[0] + "'");
- String sql = "select * from tb_student where sex like '" + args[0] + "'";
- System.out.println("sql" + sql);
- rs = stmt.executeQuery(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 (stmt != null) {
- stmt.close();
- }
- if (conn != null) {
- conn.close();
- }
- } catch(SQLException e) {
- }
- }
- }
- }