使用 Java 对 MySQL 表中的列进行计数


对此,请使用 ResultSetMetaData。我们首先创建一个表 −

mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentFirstName varchar(20),
   -> StudentLastName varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)

Java 代码如下 −

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class ResultSetDemo {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      Statement st = null;
      ResultSet rs = null;
      try {
         con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useSSL=false", "root", "123456");
         String query = "select StudentId,StudentFirstName,StudentLastName from DemoTable";
         st = con.createStatement();
         rs = st.executeQuery(query);
         ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
         int numberOfColumn = rsmd.getColumnCount();
         System.out.println(" Number Of Columns: " + numberOfColumn);
         System.out.println("All Details Of Columns:");
         for (int i = 1; i <= numberOfColumn; i++) {
            String columnName = rsmd.getColumnName(i);
            String dataTypeOfColumn = rsmd.getColumnTypeName(i);
            System.out.println(columnName + " has data type " + dataTypeOfColumn);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

输出

Number Of Columns: 3
All Details Of Columns:
StudentId has data type INT
StudentFirstName has data type VARCHAR
StudentLastName has data type VARCHAR

输出的快照如下 −

更新于: 11-12-2019

328 次浏览

开启你的 职业生涯

完成课程以获得证书

开始学习
广告