使用JDBC向数据库添加数据需要以下步骤:
1. 导入JDBC相关的类和包:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
```
2. 连接到数据库:
```java
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "username";
String password = "password";
// 创建数据库连接
Connection connection = DriverManager.getConnection(url, username, password);
```
3. 创建SQL语句:
```java
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
```
4. 创建Statement对象并执行SQL语句:
```java
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
```
5. 关闭连接和Statement对象:
```java
statement.close();
connection.close();
```
完整的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JdbcExample {
public static void main(String[] args) {
try {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "username";
String password = "password";
// 创建数据库连接
Connection connection = DriverManager.getConnection(url, username, password);
// 创建SQL语句
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
// 创建Statement对象并执行SQL语句
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
// 关闭连接和Statement对象
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意:在使用JDBC添加数据之前,需要确保数据库连接信息、SQL语句和表结构都是正确的。