如何使用JDBC API在数据库中创建表?
A. 你可以使用CREATE TABLE查询在数据库中创建表。
语法
CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) );
要使用JDBC API在数据库中创建表,你需要:
- 注册驱动程序:使用**DriverManager**类的**registerDriver()**方法注册驱动程序类。将驱动程序类名作为参数传递。
- 建立连接:使用**DriverManager**类的**getConnection()**方法连接到数据库。将URL(字符串)、用户名(字符串)、密码(字符串)作为参数传递。
- 创建Statement对象:使用**Connection**接口的**createStatement()**方法创建一个Statement对象。
- 执行查询:使用Statement接口的execute()方法执行查询。
示例
下面的JDBC程序建立与MySQL的连接,并在名为**SampleDB**的数据库中创建一个名为customers的表。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class CreateTableExample { 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://localhost/SampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to create a table String query = "CREATE TABLE CUSTOMERS(" + "ID INT NOT NULL, " + "NAME VARCHAR (20) NOT NULL, " + "AGE INT NOT NULL, " + "SALARY DECIMAL (18, 2), " + "ADDRESS CHAR (25) , " + "PRIMARY KEY (ID))"; stmt.execute(query); System.out.println("Table Created......"); } }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Connection established...... Table Created......
在MySQL中,show tables命令会显示当前数据库中的表列表。
如果你验证名为sampledb的数据库中的表列表,你可以在其中看到新创建的表,如下所示:
mysql> show tables; +--------------------+ | Tables_in_sampledb | +--------------------+ | articles | | customers | | dispatches | | technologies | | tutorial | +--------------------+ 5 rows in set (0.00 sec)
广告