如何基於JDBC結果集建立MySQL表?
ResultSetMetadata 類提供了各種方法,可以獲取當前 ResultSet 物件的資訊,例如列數、表名、列名、列的資料型別等等。
要準備CREATE查詢,您需要獲取:
- 表名,使用 getTableName() 方法。
- 列數,使用 getColumnCount() 方法迭代列。
- 每列的名稱,使用 getColumnName() 方法。
- 每列的資料型別,使用 getColumnTypeName() 方法。
- 每列的精度,使用 getPrecision() 方法。
示例
讓我們使用如下所示的 CREATE 查詢在 MySQL 資料庫中建立一個名為 customers 的表:
CREATE TABLE Customers ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, SALARY DECIMAL (18, 2), ADDRESS VARCHAR (25), PRIMARY KEY (ID) );
下面的JDBC程式在資料庫中建立另一個名為 customers2 的表。
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 CreatingTableFromReusultSet {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql:///sampledatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to retrieve records
String query = "Select * from Customers";
//Executing the query
ResultSet rs = stmt.executeQuery(query);
//retrieving the ResultSetMetaData object
ResultSetMetaData resultSetMetaData = rs.getMetaData();
//Retrieving the column count of the current table
int columnCount = resultSetMetaData.getColumnCount();
String createQuery = "CREATE TABLE "
+resultSetMetaData.getTableName(1)+"2 (";
String createQuery2 = "";
for(int i = 1; i<columnCount; i++ ) {
createQuery2 = createQuery2+
resultSetMetaData.getColumnName(i)+
" "+resultSetMetaData.getColumnTypeName(i)
+"("+resultSetMetaData.getPrecision(i)+"), ";
}
createQuery2 = createQuery2+
resultSetMetaData.getColumnName(columnCount)+
" "+resultSetMetaData.getColumnTypeName(columnCount)
+"("+resultSetMetaData.getPrecision(columnCount)+") ) ";
System.out.println("Query to create new table: ");
System.out.println(createQuery+createQuery2);
stmt.execute(createQuery+createQuery2);
System.out.println("Table created .......");
}
}輸出
Connection established...... Query to create new table: CREATE TABLE customers2 (ID INT(11), NAME VARCHAR(20), AGE INT(11), SALARY DECIMAL(18), ADDRESS VARCHAR(25) ) Table created ......
注意 - 這可能不適用於不需要宣告精度的那些資料型別。例如,日期型別。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP