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


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

CREATE TABLE new_table as SELECT * from old_table;

假设我们有一个名为 dispatches 的表,其中包含 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://127.0.0.1/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......

如果您验证 Sales 表的内容,您可以观察到它与 dispatches 表创建相同。

mysql> 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)

更新于: 30-Jul-2019

376 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告