package cc.openhome;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
public class MessageDAOJdbcImpl implements MessageDAO {
private DataSource dataSource;
public MessageDAOJdbcImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public List<Message> messagesBy(String username) {
try(Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM t_message WHERE name = ?")) {
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
List<Message> messages = new ArrayList<>();
while(rs.next()) {
messages.add(new Message(
rs.getString(1),
rs.getLong(2),
rs.getString(3))
);
}
return messages;
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void createMessage(Message message) {
try(Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement("INSERT INTO t_message(name, time, blabla) VALUES(?, ?, ?)")) {
stmt.setString(1, message.getUsername());
stmt.setLong(2, message.getMillis());
stmt.setString(3, message.getBlabla());
stmt.executeUpdate();
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteMessageBy(String username, String millis) {
try(Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement("DELETE FROM t_message WHERE name = ? AND time = ?")) {
stmt.setString(1, username);
stmt.setLong(2, Long.parseLong(millis));
stmt.executeUpdate();
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public List<Message> newestMessages(int n) {
try(Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM t_message ORDER BY time DESC LIMIT ?")) {
stmt.setInt(1, n);
ResultSet rs = stmt.executeQuery();
List<Message> messages = new ArrayList<>();
while(rs.next()) {
messages.add(new Message(
rs.getString(1),
rs.getLong(2),
rs.getString(3))
);
}
return messages;
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
}
Web原理及应用:微博—数据持久化
需积分: 11 155 浏览量
2022-09-22
11:14:03
上传
评论
收藏 16KB ZIP 举报
张小花-Soleil
- 粉丝: 421
- 资源: 6
最新资源
- 1_1、_NET Core 基础理论.vep
- 2_2、源码编译与解读(难度大,可最后看).vep
- (Linux环境下C语言)学生管理系统
- 基于STM32F103单片机(寄存器版)+OV7725摄像头模块照相机实验实验例程源码.zip
- 基于Python实现的桥梁易损性分析源码+代码注释.zip
- 基于python开发使用深度学习去预测股票后续的价格+源码+文档(毕业设计&课程设计&项目开发)
- flowable-designer-5.22.0.zip
- threadmanager.cpp
- 腾讯云小程序 - 一站式开发与部署平台
- 基于JSP+Java+Servlet采用MVC模式开发的购物网站+源码(毕业设计&课程设计&项目开发)
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
评论0