Java 面试准备系列3-JDBC

6 篇文章 0 订阅

1.建立连接:

Class.forName = ("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection(DB_URL,USER,PASSWD);

2.进行交互:

JDBC Statement, CallableStatement 和 PreparedStatement 接口定义的方法和属性,使可以发送SQL或PL/SQL命令和从数据库接收数据。

    2.1 Statement

创建对象

Statement stmt = null;
try {
   stmt = conn.createStatement( );
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

boolean execute(String SQL) : 如果ResultSet对象可以被检索返回布尔值true,否则返回false。使用这个方法来执行SQL DDL语句,或当需要使用真正的动态SQL。
int executeUpdate(String SQL) : 返回受影响的SQL语句执行的行的数目。使用此方法来执行,而希望得到一些受影响的行的SQL语句 - 例如,INSERT,UPDATE或DELETE语句。
ResultSet executeQuery(String SQL) : 返回ResultSet对象。当希望得到一个结果集使用此方法,就像使用一个SELECT语句。

     2.2 PreparedStatement

创建对象

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}
       执行

String sql = "UPDATE Employees set age=? WHERE id=?";
      stmt = conn.prepareStatement(sql);
      
      //Bind values into the parameters.
      stmt.setInt(1, 35);  // This would set age
      stmt.setInt(2, 102); // This would set ID
      
      // Let us update age of the record with ID = 102;
      int rows = stmt.executeUpdate();
      System.out.println("Rows impacted : " + rows );

      // Let us select all the records and display them.
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值