动力节点笔记
- 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) {
- }
- }
- }
- }