共計(jì) 1100 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中將數(shù)組里的數(shù)據(jù)存入數(shù)據(jù)庫(kù)通常需要通過(guò) JDBC(Java Database Connectivity)來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的示例代碼來(lái)實(shí)現(xiàn)這個(gè)功能:
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 = "root";
String password = "password";
Connection connection = null;
PreparedStatement preparedStatement = null;
try {connection = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO mytable (column_name) VALUES (?)";
preparedStatement = connection.prepareStatement(sql);
int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {preparedStatement.setInt(1, array[i]);
preparedStatement.executeUpdate();}
System.out.println("Data inserted successfully");
} catch (SQLException e) {e.printStackTrace();
} finally {
try {if (preparedStatement != null) {preparedStatement.close();
}
if (connection != null) {connection.close();
}
} catch (SQLException e) {e.printStackTrace();
}
}
}
}
在上面的代碼中,首先創(chuàng)建了與數(shù)據(jù)庫(kù)的連接,然后準(zhǔn)備一個(gè) INSERT 語(yǔ)句用于插入數(shù)據(jù)。接著定義一個(gè)整型數(shù)組,通過(guò)循環(huán)遍歷數(shù)組中的每個(gè)元素,并將其插入到數(shù)據(jù)庫(kù)中。最后關(guān)閉連接和預(yù)處理語(yǔ)句。這只是一個(gè)簡(jiǎn)單的示例,實(shí)際情況中可能需要根據(jù)具體需求進(jìn)行調(diào)整。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2024-03-19