JDBC - Statement 对象示例



以下是示例,它使用了以下三个查询以及打开和关闭语句:

  • 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 语句一样。

此示例代码是根据前面章节中完成的环境和数据库设置编写的。

更新表中记录的示例

在此示例中,我们有五个静态字符串,包含数据库连接 URL、用户名、密码、UPDATE 查询和 SELECT 查询。现在使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。连接准备就绪后,我们使用 connection.createStatement() 方法创建了一个 Statement 对象。现在使用 statement.executeUpdate(),我们运行了更新查询。最后使用 statement.executeQuery(),执行 SELECT 查询并将结果存储在结果集中。现在迭代结果集并打印每个记录以检查更新的内容。

将以下示例复制并粘贴到 JDBCStatementExample.java 中,编译并运行如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementExample {
   static final String DB_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT id, first, last, age FROM Employees";
   static final String UPDATE_QUERY = "UPDATE Employees set age=30 WHERE id=103";

   public static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
         ) {
         // Let us check if it returns a true Result Set or not.
         Boolean ret = stmt.execute(UPDATE_QUERY);
         System.out.println("Return value is : " + ret.toString() );

         // Let us update age of the record with ID = 103;
         int rows = stmt.executeUpdate(UPDATE_QUERY);
         System.out.println("Rows impacted : " + rows );

         // Let us select all the records and display them.
         ResultSet rs = stmt.executeQuery(QUERY);		      

         // Extract data from result set
         while (rs.next()) {
            // Retrieve by column name
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", First: " + rs.getString("first"));
            System.out.println(", Last: " + rs.getString("last"));
         }
         rs.close();
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

输出

现在让我们按如下方式编译上述示例:

C:\>javac JDBCStatementExample.java
C:\>

运行JDBCStatementExample时,它会产生以下结果:

C:\>java JDBCStatementExample
Return value is : false
Rows impacted : 1
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mehnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
C:\>

从表中删除记录的示例

在此示例中,我们有四个静态字符串,包含数据库连接 URL、用户名、密码、SELECT 查询和 DELETE 查询。现在使用 DriverManager.getConnection() 方法,我们准备了一个数据库连接。连接准备就绪后,我们使用 connection.createStatement() 方法创建了一个 Statement 对象。现在使用 statement.executeUpdate(),我们运行了删除查询。最后使用 statement.executeQuery(),执行 SELECT 查询并将结果存储在结果集中。现在迭代结果集并打印每个记录以检查已删除的内容。

将以下示例复制并粘贴到 DeleteExample.java 中,编译并运行如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementExample {
   static final String DB_URL = "jdbc:mysql://127.0.0.1/TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT StudentID, LastName, FirstName, Address, Dept FROM Students";
   static final String DELETE_QUERY = "DELETE FROM Students WHERE StudentID='1005'";

   public static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
      ) {
         //Check if it returns a true Result Set or not.
         boolean ret = stmt.execute(DELETE_QUERY);

         // Insert a new record;
         int rows = stmt.executeUpdate(DELETE_QUERY);
         System.out.println("Rows impacted : " + rows );

         // Select all the records and display them.
         ResultSet rs = stmt.executeQuery(QUERY);		      

         // Extract data from result set
         while (rs.next()) {
            // Retrieve by column name
            System.out.print("StudentID: " + rs.getInt("Studentid"));
            System.out.print(", LastName: " + rs.getString("LastName"));
            System.out.print(", FirstName: " + rs.getString("FirstName"));
            System.out.println(", Address: " + rs.getString("Address"));
            System.out.println(", Dept: " + rs.getString("Dept"));
         }
         rs.close();
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

输出

现在让我们按如下方式编译上述示例:

C:\>javac JDBCStatementExample.java
C:\>

运行JDBCStatementExample时,它会产生以下结果:

C:\>java JDBCStatementExample
Rows impacted : 1
StudentID: 1000, LastName: Agarwal, FirstName: Bonny Address: 12 Southern Ave
 Dept: Chemistry
StudentID: 1001, LastName: Pandey, FirstName: Amit Address: 23 Bahadur Shah Zafar Marg
 Dept: Physics
StudentID: 1002, LastName: Kumar, FirstName: Shefali Address: 4 Middleton Row
 Dept: English
StudentID: 1004, LastName: Ali, FirstName: Mohammed Address: 49/2B Ganesh Ch Ave

C:\>
jdbc-statements.htm
广告