java 如何遍历map,插入数据库
时间: 2023-05-03 12:06:01 浏览: 338
遍历Map可以使用Java中的迭代器或for-each循环,如下所示:
```
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
// 使用迭代器遍历Map
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
// 插入数据库操作
}
// 使用for-each循环遍历Map
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// 插入数据库操作
}
```
插入数据库可以使用JDBC进行操作,具体步骤为:
1. 加载JDBC驱动程序
```
Class.forName("com.mysql.jdbc.Driver");
```
2. 建立数据库连接
```
Connection conn = DriverManager.getConnection(url, username, password);
```
3. 创建PreparedStatement对象
```
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
```
4. 给PreparedStatement对象设置参数
```
ps.setString(1, "value1");
ps.setString(2, "value2");
```
5. 执行插入操作
```
ps.executeUpdate();
```
6. 关闭PreparedStatement和连接对象
```
ps.close();
conn.close();
```
完整插入数据库操作示例代码:
```
// 假设map已经存在并且填充了数据
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "username";
String password = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// 设置PreparedStatement参数
ps.setString(1, key);
ps.setObject(2, value);
// 执行插入操作
ps.executeUpdate();
}
ps.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
```
阅读全文