在java.sql.Types中的类表示整数形式的SQL数据类型。valueOf()枚举JDBCType的方法接受一个表示java.sql.Type的整数值,并返回与指定值相对应的JDBC类型。
示例
让我们使用CREATE语句在MySQL数据库中创建一个名为MyPlayers的表,如下所示-CREATE TABLE MyPlayers(
ID INT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (ID)
);
接下来的JDBC程序与MySQL数据库建立连接,将MyPlayers表的内容检索到ResultSet对象中,获取其元数据,获取表中所有列的列类型为java.sql.Types值(整数),并检索使用valueOf()方法的相应类型的名称。
示例import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.JDBCType;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLTypeName {
public static void main(String args[]) throws SQLException {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获得连接
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//创建语句
Statement stmt = con.createStatement();
//查询以检索记录
String query = "Select * from MyPlayers";
//执行查询
ResultSet rs = stmt.executeQuery(query);
//获取ResultSetMetadata对象
ResultSetMetaData mertadata = rs.getMetaData();
//返回指定列的java.sql.Type名称
//检索列的数据类型
int ID_Type = mertadata.getColumnType(1);
int FirstName_Type = mertadata.getColumnType(2);
int LastName_Type = mertadata.getColumnType(3);
int DateOfBirth_Type = mertadata.getColumnType(4);
int PlaceOfBirth_Type = mertadata.getColumnType(5);
int Country_Type = mertadata.getColumnType(6);
System.out.println("Data type of the column ID: "+JDBCType.valueOf(ID_Type));
System.out.println("Data type of the column First_Name: "+JDBCType.valueOf(FirstName_Type));
System.out.println("Data type of the column Last_Name: "+JDBCType.valueOf(LastName_Type));
System.out.println("Data type of the column Date_Of_Birth: "+JDBCType.valueOf(DateOfBirth_Type));
System.out.println("Data type of the column Place_Of_Birth: "+JDBCType.valueOf(PlaceOfBirth_Type));
System.out.println("Data type of the column Country: "+JDBCType.valueOf(Country_Type));
}
}
输出结果Connection established......
Price values updated ......
Contents of the Sales table after the update:
Name: Key-Board, Customer Name: Raja, Dispatch Date: 2019-09-01, Delivery Time: 11:00:00, Price: 8500, Location: Hyderabad
Name: Earphones, Customer Name: Roja, Dispatch Date: 2019-05-01, Delivery Time: 11:00:00, Price: 2000, Location: Vishakhapatnam
Name: Mouse, Customer Name: Puja, Dispatch Date: 2019-03-01, Delivery Time: 10:59:59, Price: 4500, Location: Vijayawada
Name: Mobile, Customer Name: Vanaja, Dispatch Date: 2019-03-01, Delivery Time: 10:10:52, Price: 9000, Location: Chennai
Name: Headset, Customer Name: Jalaja, Dispatch Date: 2019-04-06, Delivery Time: 11:08:59, Price: 7500, Location: Goa