使用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語句和表結構都是正確的。