使用 Java JDBC 對 MySQL 進行“count”查詢,其返回型別是什麼?


Count 的返回型別是 long。Java 語句如下

rs.next();
long result= rs.getLong("anyAliasName");

首先,在示例資料庫 test3 中建立一個包含一些記錄的表。建立表的查詢如下

mysql> create table CountDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令在表中插入一些記錄。

查詢如下

mysql> insert into CountDemo(Name) values('John');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountDemo(Name) values('Carol');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountDemo(Name) values('Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into CountDemo(Name) values('David');
Query OK, 1 row affected (0.16 sec)

使用 select 語句顯示錶中的所有記錄。

查詢如下

mysql> select *from CountDemo;

以下為輸出

+----+-------+
| Id | Name  |
+----+-------+
| 1 | John   |
| 2 | Carol  |
| 3 | Bob    |
| 4 | David  |
+----+-------+
4 rows in set (0.00 sec)

以下是使用 Java JDBC 對 MySQL 進行“count”查詢的 Java 程式碼返回型別

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ReturnTypeOfCount {
   public static void main(String[] args) {
      Connection con=null;
      Statement st=null;
      ResultSet rs=null;
      try {
         con=DriverManager.getConnection("jdbc:mysql://:3306/test3?useSSL=false",
         "root","123456");
         String yourQuery = "SELECT COUNT(*) AS totalCount FROM CountDemo";
         st = con.createStatement();
         rs = st.executeQuery(yourQuery);
         rs.next();
         long result= rs.getLong("totalCount");
         System.out.println("Total Count="+result);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

以下為輸出

Total Count=4
Here is the snapshot of the output:

更新日期: 30-Jul-2019

394 瀏覽

開啟你的事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.