如何使用 JDBC 获取表中列的数据类型?
可以使用 ResultSetMetaData 类的 getColumnType() 方法获取表中列的数据类型。
//Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type String column_name = rsmd.getColumnTypeName(2);
假设我们在数据库中有一个名为 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 TypeOfColumn { 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 String column_name = rsmd.getColumnTypeName(3); System.out.println("Data type of the column with the specified index is: "+column_name); } }
输出
Connection established...... Data type of the column with the specified index is: DATE
广告