JDBC 中的語句是什麼?


Statement 介面表示靜態 SQL 語句,它用於使用 Java 程式建立和執行通用 SQL 語句。

建立語句

你可以使用 connection 介面的 createStatement() 方法建立此介面的一個物件。透過呼叫此方法如下所示建立語句。

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

執行 Statement 物件

建立語句物件後,你可以使用 execute()、executeUpdate() 和 executeQuery() 等執行方式中的一種來執行語句。

  • execute():此方法用於執行 SQL DDL 語句,它返回一個布林值,指定是否可以檢索 ResultSet 物件。

  • executeUpdate():此方法用於執行諸如插入、更新、刪除等語句。它返回一個表示受影響的行數的整數值。

  • executeQuery():此方法用於執行返回表格資料(例如 SELECT 語句)的語句。它返回 ResultSet 類的一個物件。

示例

以下 JDBC 應用程式演示如何建立和執行語句。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StatementExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());

      //Getting the connection
      String mysqlUrl = "jdbc:mysql:///testdb";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");

      //Creating the Statement
      Statement stmt = con.createStatement();

      //Executing the statement
      String createTable = "CREATE TABLE Employee(“
         + "Name VARCHAR(255), "
         + "Salary INT NOT NULL, "
         + "Location VARCHAR(255))";
      boolean bool = stmt.execute(createTable);

      String insertData = "INSERT INTO Employee("
         + "Name, Salary, Location) VALUES "
         + "('Amit', 30000, 'Hyderabad'), "
         + "('Kalyan', 40000, 'Vishakhapatnam'), "
         + "('Renuka', 50000, 'Delhi'), "
         + "('Archana', 15000, 'Mumbai')";
      int i = stmt.executeUpdate(insertData);
      System.out.println("Rows inserted: "+i);
      ResultSet rs = stmt.executeQuery("Select *from Employee");

      while(rs.next()) {
         System.out.print("Name: "+rs.getString("Name")+", ");
         System.out.print("Salary: "+rs.getInt("Salary")+", ");
         System.out.print("City: "+rs.getString("Location"));
         System.out.println();
      }
   }
}

輸出

Connection established......
Rows inserted: 4
Name: Amit, Salary: 30000, City: Hyderabad
Name: Kalyan, Salary: 40000, City: Vishakhapatnam
Name: Renuka, Salary: 50000, City: Delhi
Name: Archana, Salary: 15000, City: Mumbai

更新於: 2019 年 7 月 30 日

726 次瀏覽

啟動您的 事業

完成課程認證

開始
廣告
© . All rights reserved.