使用Java语言创建和插入表需要以下步骤:
- 连接到数据库
可以使用JDBC API中提供的DriverManager类从Java代码中连接到数据库。例如,对于MySQL数据库,可以使用如下代码:
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_database", "username", "password");
其中,“com.mysql.jdbc.Driver”是MySQL JDBC驱动程序的类名,“jdbc:mysql://localhost:3306/my_database”指定了数据库的URL,“username”和“password”是连接数据库所需的用户名和密码。
- 创建表
要创建一个新表,可以使用Java的Statement类并执行CREATE TABLE语句。例如,以下代码创建了一个名为“students”的新表:
Statement statement = connection.createStatement();
String createTableSQL = "CREATE TABLE students (id INT NOT NULL, name VARCHAR(50), age INT, PRIMARY KEY (id))";
statement.executeUpdate(createTableSQL);
此处,使用createStatement()方法创建一个新的Statement对象,然后使用executeUpdate()方法执行CREATE TABLE语句。CREATE TABLE语句指定了新表的名称“students”和表中的字段id、name和age。
- 插入记录
要在表中插入新记录,可以使用Java的PreparedStatement类并执行INSERT语句。例如,以下代码向“students”表中插入一条记录:
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO students (id, name, age) VALUES (?, ?, ?)");
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "John");
preparedStatement.setInt(3, 20);
preparedStatement.executeUpdate();
此处,使用prepareStatement()方法创建一个新的PreparedStatement对象,然后使用setInt()和setString()方法设置插入记录的值。在执行INSERT语句之后,使用executeUpdate()方法将记录插入到“students”表中。
完整的示例代码如下:
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_database", "username", "password");
// 创建新表
Statement statement = connection.createStatement();
String createTableSQL = "CREATE TABLE students (id INT NOT NULL, name VARCHAR(50), age INT, PRIMARY KEY (id))";
statement.executeUpdate(createTableSQL);
// 插入记录
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO students (id, name, age) VALUES (?, ?, ?)");
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "John");
preparedStatement.setInt(3, 20);
preparedStatement.executeUpdate();
// 关闭连接
preparedStatement.close();
statement.close();
connection.close();
}
}
当然,实际应用中还需注意安全性,例如可以使用JDBC的防止SQL注入的方式等。