Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ชนิดข้อมูลที่คืนค่าจาก COUNT query ใน MySQL ผ่าน Java JDBC

ชนิดข้อมูลที่คืนค่าจาก COUNT(*) คือ long ใน Java รหัสคำสั่งคือดังนี้

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

สร้างตารางตัวอย่าง

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

เพิ่มข้อมูลตัวอย่าง

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)

แสดงข้อมูลทั้งหมด

mysql> select * from CountDemo;

ผลลัพธ์:

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

โค้ด Java สำหรับดึงผลลัพธ์ COUNT

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://localhost: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

ข้อสังเกตสำคัญ

  • MySQL ส่งคืน BIGINT สำหรับ COUNT(*) ซึ่งตรงกับ long ใน Java
  • ควรใช้ getLong() แทน getInt() เพื่อป้องกัน overflow เมื่อจำนวนแถวมาก
  • ควรใช้ try-with-resources (Java 7+) เพื่อปิด Connection, Statement, ResultSet อัตโนมัติ
  • ในโปรดักชันจริง ควรใช้ PreparedStatement และ connection pool