如何在JDBC中使用另一个表创建表?

您可以使用以下语法创建与现有表相同的表:

CREATE TABLE new_table as SELECT * from old_table;

假设我们有一个名为dispatchs的表,其中包含5条记录,如下所示:

+-------------+--------------+--------------+--------------+-------+----------------+
| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location       |
+-------------+--------------+--------------+--------------+-------+----------------+
| Key-Board   | Raja         | 2019-09-01   | 05:30:00     | 7000  | Hyderabad      |
| Earphones   | Roja         | 2019-05-01   | 05:30:00     | 2000  | Vishakhapatnam |
| Mouse       | Puja         | 2019-03-01   | 05:29:59     | 3000  | Vijayawada     |
| Mobile      | Vanaja       | 2019-03-01   | 04:40:52     | 9000  | Chennai        |
| Headset     | Jalaja       | 2019-04-06   | 18:38:59     | 6000  | Goa            |
+-------------+--------------+--------------+--------------+-------+----------------+

接下来的JDBC程序建立与数据库的连接,并使用现有表的定义创建一个新表。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTable {
   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://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement object
      Statement stmt = con.createStatement();
      //Query to create a table
      String query = "CREATE TABLE Sales as SELECT * from dispatches";
      //Executing the query
      stmt.execute(query);
      System.out.println("Table created......");
   }
}

输出结果

Connection established......
Table created......

如果您验证“销售”表的内容,则可以观察到它与“分派”表相同。

select * from Sales;
+-------------+--------------+--------------+--------------+-------+----------------+
| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location       |
+-------------+--------------+--------------+--------------+-------+----------------+
| Key-Board   | Raja         | 2019-09-01   | 05:30:00     | 7000  | Hyderabad      |
| Earphones   | Roja         | 2019-05-01   | 05:30:00     | 2000  | Vishakhapatnam |
| Mouse       | Puja         | 2019-03-01   | 05:29:59     | 3000  | Vijayawada     |
| Mobile      | Vanaja       | 2019-03-01   | 04:40:52     | 9000  | Chennai        |
| Headset     | Jalaja       | 2019-04-06   | 18:38:59     | 6000  | Goa            |
+-------------+--------------+--------------+--------------+-------+----------------+
5 rows in set (0.00 sec)