给我举例JAVA一个定时任务存储json字符串查询数据于一个字段的数据表编码
时间: 2024-05-15 17:15:50 浏览: 110
使用java执行定时任务示例
以下是一个JAVA定时任务存储JSON字符串并查询数据表的示例代码:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONObject;
public class JsonStorageTask extends TimerTask {
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "password";
private static final String TABLE_NAME = "mytable";
private static final String COLUMN_NAME = "json_data";
private Connection connection;
public JsonStorageTask() {
try {
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void run() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = Calendar.getInstance().getTime();
String timestamp = dateFormat.format(now);
JSONObject data = new JSONObject();
data.put("timestamp", timestamp);
data.put("value", Math.random() * 100);
String jsonData = data.toString();
storeJsonData(jsonData);
queryJsonData();
}
private void storeJsonData(String jsonData) {
try {
String sql = "INSERT INTO " + TABLE_NAME + " (" + COLUMN_NAME + ") VALUES (?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, jsonData);
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void queryJsonData() {
try {
String sql = "SELECT * FROM " + TABLE_NAME;
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String jsonData = resultSet.getString(COLUMN_NAME);
JSONObject data = new JSONObject(jsonData);
System.out.println("Timestamp: " + data.getString("timestamp"));
System.out.println("Value: " + data.getDouble("value"));
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new JsonStorageTask(), 0, 5000); // run every 5 seconds
}
}
```
这个示例代码会在每5秒钟执行一次定时任务,生成一个JSON字符串并存储到数据库中,然后查询数据表并打印出来。JSON字符串中包含一个时间戳和一个随机数值。在存储和查询数据时,使用了预编译的SQL语句,可以防止SQL注入攻击。注意修改DB_URL、DB_USER、DB_PASSWORD、TABLE_NAME和COLUMN_NAME等常量的值以适配你自己的环境。
阅读全文