如何用 JDBC 获取表中一列的大小?
你可以使用 ResultSetMetaData 类的 getPrecision() 方法获取表的列的大小。
//Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type int size_name = rsmd. getPrecision(3);
假设我们在数据库中有一张名为 employee_data 的表,描述如下所示
+----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | Name | varchar(255) | YES | | NULL | | | Dob | date | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+
以下 JDBC 程序与数据库建立连接,检索 employee_data 表的 ResultSetMetaData 对象,并打印第三列的大小。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; public class SizeOfColumn { public static void main(String args[])throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from employee_data"); //Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type int column_size = rsmd.getPrecision(3); System.out.println("Size of the 3rd column : "+column_size); } }
输出
Connection established...... Size of the 3rd column : 11
广告