您可以使用ResultSetMetaData接口的 getTableName()方法在当前ResultSet对象中获取表的名称。此方法接受代表列索引的整数值,并返回代表包含给定列的表名称的String值。
让我们使用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) );
现在,我们将使用INSERT语句在MyPlayers 表中插入7条记录-
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
以下JDBC程序建立与MySQL数据库的连接,检索并显示表的名称。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class ResultSetMetaData_getTableName { 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 resultSetMetaData = rs.getMetaData(); //检索列名 String tableName = resultSetMetaData.getTableName(4); System.out.println("Name of the table : "+ tableName); } }
输出结果
Connection established...... Name of the table: myplayers