写一段java 往数据库里插入数组的代码,数据库表为order,插入列为start_city,end_city,start_time,price,flight_number,username
时间: 2024-02-11 17:09:03 浏览: 67
如何用java代码写数据库数据
5星 · 资源好评率100%
假设order表中的各个列的数据类型都为字符串类型(VARCHAR),以下是向order表中插入数组的示例代码:
```java
import java.sql.*;
import java.util.Arrays;
public class InsertOrder {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "mypassword";
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 建立数据库连接
conn = DriverManager.getConnection(url, user, password);
// 准备插入语句
pstmt = conn.prepareStatement("INSERT INTO order (start_city, end_city, start_time, price, flight_number, username) VALUES (?, ?, ?, ?, ?, ?)");
// 假设要插入的数据数组如下
String[] start_cities = {"Beijing", "Shanghai", "Guangzhou"};
String[] end_cities = {"Shanghai", "Guangzhou", "Beijing"};
String[] start_times = {"2021-08-01 08:00:00", "2021-08-02 12:00:00", "2021-08-03 18:00:00"};
String[] prices = {"1000", "2000", "1500"};
String[] flight_numbers = {"CA123", "MU456", "CZ789"};
String[] usernames = {"Alice", "Bob", "Charlie"};
// 逐个插入数据到数据库中
for (int i = 0; i < start_cities.length; i++) {
pstmt.setString(1, start_cities[i]);
pstmt.setString(2, end_cities[i]);
pstmt.setString(3, start_times[i]);
pstmt.setString(4, prices[i]);
pstmt.setString(5, flight_numbers[i]);
pstmt.setString(6, usernames[i]);
pstmt.executeUpdate();
}
System.out.println("插入数据成功!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
上述代码中,先建立数据库连接,然后通过PreparedStatement对象执行INSERT语句,逐个插入数组中的数据到对应的列中。注意,在执行SQL语句时,列名order需要用反引号(`)括起来,否则会报错。最后关闭数据库连接。
阅读全文