如何在 JDBC 中使用另一个表创建表?
jdbcjava 8object oriented programmingprogramming
您可以使用以下语法创建与现有表相同的表:
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{ //注册驱动程序 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 对象 Statement stmt = con.createStatement(); //查询以创建表 String query = "CREATE TABLE Sales as SELECT * from dispatches"; //执行查询 stmt.execute(query); System.out.println("Table created......"); } }
输出
Connection established...... Table created......
如果您验证销售表的内容,您会发现其创建内容与调度表相同。
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)