playframework中用jdbc进行数据库操作

不变的常量:

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清除一下。


你可能感兴趣的:(playframework中用jdbc进行数据库操作)