java将json数据导入数据库
时间: 2023-12-10 15:39:37 浏览: 61
将 JSON 数据导入数据库的一般流程如下:
1. 读取 JSON 数据
2. 解析 JSON 数据为 Java 对象
3. 连接数据库
4. 将 Java 对象转换为数据库中的记录
5. 插入记录到数据库中
下面是一个示例代码,假设 JSON 数据格式如下:
```json
[
{
"id": 1,
"name": "Alice",
"age": 20
},
{
"id": 2,
"name": "Bob",
"age": 25
}
]
```
Java 代码如下:
```java
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Main {
public static void main(String[] args) throws Exception {
// 1. 读取 JSON 数据
FileReader reader = new FileReader("data.json");
// 2. 解析 JSON 数据为 Java 对象
Gson gson = new Gson();
List<Person> persons = gson.fromJson(reader, new TypeToken<List<Person>>() {}.getType());
// 3. 连接数据库
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
// 4. 将 Java 对象转换为数据库中的记录
PreparedStatement stmt = conn.prepareStatement("INSERT INTO persons (id, name, age) VALUES (?, ?, ?)");
for (Person person : persons) {
stmt.setInt(1, person.getId());
stmt.setString(2, person.getName());
stmt.setInt(3, person.getAge());
stmt.executeUpdate();
}
// 5. 插入记录到数据库中
stmt.close();
conn.close();
}
}
class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
这个示例代码使用了 Google Gson 库来解析 JSON 数据为 Java 对象,使用了 JDBC 来连接 MySQL 数据库。请根据自己的需求修改连接字符串、账号密码等参数。
阅读全文
相关推荐
















