java json导入mysql
时间: 2023-10-16 20:33:38 浏览: 44
要将 JSON 数据导入 MySQL 数据库,可以使用以下步骤:
1. 创建一个 MySQL 表来存储 JSON 数据。
例如,假设你有一个名为 `students` 的表,其中包含以下列:`id`、`name`、`age` 和 `address`。在这个表中,你想要存储学生的信息。
```
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
address VARCHAR(100)
);
```
2. 准备 JSON 数据并将它们转换为 SQL 语句。
例如,你有以下 JSON 数据:
```
[
{
"id": 1,
"name": "Alice",
"age": 20,
"address": "New York"
},
{
"id": 2,
"name": "Bob",
"age": 21,
"address": "Los Angeles"
}
]
```
你可以将它们转换为 SQL 语句:
```
INSERT INTO students (id, name, age, address) VALUES
(1, 'Alice', 20, 'New York'),
(2, 'Bob', 21, 'Los Angeles');
```
你可以使用 Java 中的 `JSONArray` 和 `JSONObject` 类来解析 JSON 字符串并创建 SQL 语句。
例如:
```java
String jsonString = "[{\"id\": 1,\"name\": \"Alice\",\"age\": 20,\"address\": \"New York\"},{\"id\": 2,\"name\": \"Bob\",\"age\": 21,\"address\": \"Los Angeles\"}]";
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String address = jsonObject.getString("address");
String sql = "INSERT INTO students (id, name, age, address) VALUES (" + id + ", '" + name + "', " + age + ", '" + address + "')";
// 执行 SQL 语句
}
```
3. 将 SQL 语句执行。
你可以使用 JDBC 来连接到 MySQL 数据库并执行 SQL 语句。
例如:
```java
String url = "jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String username = "root";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement()) {
// 执行 SQL 语句
statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
```
这样,你就可以将 JSON 数据导入到 MySQL 数据库中了。