Java如何在数据库中创建表?
在此示例中,您可以看到如何在MySQL数据库中创建表。我们创建了一个称为表books具有以下字段,isbn,title,published_year和price。我们首先创建与数据库的连接,然后执行创建表查询。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class CreateTableExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { String sql = "CREATE TABLE books (" + " isbn varchar(50) NOT NULL, " + " title varchar(100) DEFAULT NULL, " + " published_year int(11) DEFAULT NULL, " + " price decimal(10,2) DEFAULT NULL, " + " PRIMARY KEY (isbn) " + ")"; Statement statement = connection.createStatement(); statement.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>