JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。MySQL是一种关系型数据库管理系统,用于存储和管理数据。
在MySQL中保存JSON数据主要有两种方式:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.json.JSONObject;
public class JsonToMySQL {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// 创建表
String createTableSQL = "CREATE TABLE IF NOT EXISTS mytable (id INT AUTO_INCREMENT PRIMARY KEY, data JSON)";
conn.createStatement().execute(createTableSQL);
// 插入JSON数据
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John Doe");
jsonObject.put("age", 30);
jsonObject.put("email", "john.doe@example.com");
String insertSQL = "INSERT INTO mytable (data) VALUES (?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
pstmt.setString(1, jsonObject.toString());
pstmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.json.JSONObject;
public class QueryJsonFromMySQL {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String querySQL = "SELECT data FROM mytable WHERE id = 1";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(querySQL)) {
if (rs.next()) {
String jsonString = rs.getString("data");
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println("Name: " + jsonObject.getString("name"));
System.out.println("Age: " + jsonObject.getInt("age"));
System.out.println("Email: " + jsonObject.getString("email"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
通过以上内容,你应该能够了解如何在Java中将JSON数据保存到MySQL数据库,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云