playframework中用jdbc进行数据库操作

本文详细介绍了数据库中常量的定义与使用,包括数据库URL、用户名和密码,并提供了具体的save和delete方法实现。同时,文章还展示了如何通过SQL查询语句进行数据筛选和条件查询,确保了操作的高效性和准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不变的常量:

public static final String DB_URL = "jdbc:mysql://127.0.0.1/db";

public static final String DB_USER = "root";

public static final String DB_PWSD = "123456";

相应的save和delete方法:

public static void saveMsg(long user_id, Timestamp create_at, String group_name, String msg) throws SQLException{ 
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = (Connection) DriverManager.getConnection(Const.DB_URL, Const.DB_USER, Const.DB_PWSD);
String insert = "insert into msg(create_at, group_name, msg, user_id) values(?,?,?,?)";
 
pstmt = (PreparedStatement) connection.prepareStatement(insert);
pstmt.setTimestamp(1, create_at);
pstmt.setString(2, group_name);
pstmt.setString(3, msg);
pstmt.setLong(4, user_id);
pstmt.executeUpdate();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

public static void deleteMsg(long user_id, String group_name) throws SQLException{ 
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = (Connection) DriverManager.getConnection(Const.DB_URL, Const.DB_USER Const.DB_PWSD);
String delete = "delete from msg  where user_id = ? and group_name = ?";

pstmt = (PreparedStatement) connection.prepareStatement(delete);

pstmt.setLong(1, user_id);
pstmt.setString(2, group_name);

pstmt.execute();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

提示:在delete时,不能用delete from msg m  where m.user_id = ? and m.group_name = ?这样不识别,语法错误,正确的写法是:delete from msg  where user_id = ? and group_name = ?

根据当前时间的查询语句:

SELECT * FROM studyplan s where s.company= "河南省中原活塞股份有限公司" and (date < date_format(NOW(),'%Y-%m-%d'));

提示:有时候连接数据库时会有缓存信息,这样就可能会出现密码错误的问题,可以先用play clean清除一下。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值