一个JSP数据库连接使用 preparedstatement 总是异常 跳到catch里的问题 我不会用preparedstatement 以下是
publicmessagegetMessageById(longmessageid){//根据message表中的字段,拼接SQL语句Stringsql="select*...
public message getMessageById(long messageid) {
// 根据message表中的字段,拼接SQL语句
String sql = "select * from message where messageid = ?";
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String url="jdbc:jtds:sqlserver://localhost:1433/muwensi";
String user="sa";
String password="sa";
message instance = null;
// 获取数据库
try {
//加载驱动程序
Class.forName("net.sourceforge.jtds.jdbc.Driver");
DriverManager.registerDriver(new net.sourceforge.jtds.jdbc.Driver());
//获取连接
con = DriverManager.getConnection(url,user,password);
stmt = con.prepareStatement(sql);
stmt.setLong(1, messageid);
// 执行sql语句,并将记录集返回给ResultSet
rs = stmt.executeQuery();
//循环ResultSet集合,并且封装Message对象
while(rs.next()){
instance = new message();
instance.setMessageid(rs.getLong("messageid"));
instance.setMessagetitile(rs.getString("messagetitle"));
instance.setMessagecontent(rs.getString("messagecontent"));
instance.setMessagedate(rs.getDate("messagedate"));
instance.setMessagetype(rs.getInt("messagetype"));
instance.setUsername(rs.getString("username"));
}
} catch (Exception ex) {
instance.setUsername("muwensi1");
} finally {
try {
// 关闭数据库连接,释放资源
rs.close();
stmt.close();
con.close();
} catch (Exception ex) {
}
}
return instance;
}
帮助解决问题了有追加分 展开
// 根据message表中的字段,拼接SQL语句
String sql = "select * from message where messageid = ?";
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String url="jdbc:jtds:sqlserver://localhost:1433/muwensi";
String user="sa";
String password="sa";
message instance = null;
// 获取数据库
try {
//加载驱动程序
Class.forName("net.sourceforge.jtds.jdbc.Driver");
DriverManager.registerDriver(new net.sourceforge.jtds.jdbc.Driver());
//获取连接
con = DriverManager.getConnection(url,user,password);
stmt = con.prepareStatement(sql);
stmt.setLong(1, messageid);
// 执行sql语句,并将记录集返回给ResultSet
rs = stmt.executeQuery();
//循环ResultSet集合,并且封装Message对象
while(rs.next()){
instance = new message();
instance.setMessageid(rs.getLong("messageid"));
instance.setMessagetitile(rs.getString("messagetitle"));
instance.setMessagecontent(rs.getString("messagecontent"));
instance.setMessagedate(rs.getDate("messagedate"));
instance.setMessagetype(rs.getInt("messagetype"));
instance.setUsername(rs.getString("username"));
}
} catch (Exception ex) {
instance.setUsername("muwensi1");
} finally {
try {
// 关闭数据库连接,释放资源
rs.close();
stmt.close();
con.close();
} catch (Exception ex) {
}
}
return instance;
}
帮助解决问题了有追加分 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询