溫馨提示×

java怎么將數(shù)組里的數(shù)據(jù)存入數(shù)據(jù)庫

小億
155
2024-02-20 09:16:54
欄目: 編程語言

可以使用Java的JDBC(Java Database Connectivity)來將數(shù)組中的數(shù)據(jù)存入數(shù)據(jù)庫。以下是一個(gè)簡單的示例代碼:

```java

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class ArrayToDatabase {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/mydatabase";

String username = "username";

String password = "password";

Connection conn = null;

try {

conn = DriverManager.getConnection(url, username, password);

int[] data = {1, 2, 3, 4, 5};

String query = "INSERT INTO mytable (column_name) VALUES (?)";

PreparedStatement preparedStatement = conn.prepareStatement(query);

for (int i = 0; i < data.length; i++) {

preparedStatement.setInt(1, data[i]);

preparedStatement.executeUpdate();

}

System.out.println("Data inserted successfully");

} catch (SQLException e) {

e.printStackTrace();

} finally {

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

}

```

在上面的示例代碼中,首先建立了與數(shù)據(jù)庫的連接,接著定義了一個(gè)整型數(shù)組`data`,然后通過PreparedStatement將數(shù)組中的數(shù)據(jù)逐個(gè)插入到數(shù)據(jù)庫表中。最后關(guān)閉數(shù)據(jù)庫連接。請根據(jù)實(shí)際情況修改數(shù)據(jù)庫連接信息、數(shù)據(jù)表名稱和字段名。

0