package com.jdbc;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
public class Select {
public Student findById(String sno){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Student s = new Student();
try {
conn = DBUtil.getConnection();
StringBuilder sb = new StringBuilder();
sb.append(" select * from student where SNO = ?");
ps = conn.prepareStatement(sb.toString());
ps.setString(1, sno);
rs = ps.executeQuery();
System.out.println(sb);
System.out.println(rs.next());
if(rs.next()){
s.setSno(rs.getString("SNO"));
s.setSname(rs.getString("SNAME"));
s.setAge(rs.getInt("AGE"));
s.setSex(rs.getString("AGR"));
s.setDept(rs.getString("DEPT"));
System.out.println(s.getSno());
return s;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps = null;
}
}
}
public static void main(String[] args) {
Select s = new Select();
Student student = s.findById("1004");
System.out.println(student);
}
/**
* 控制台输出:
* select * from student where SNO = ?
*true
*null
*/
}
1
choice4 OP 为什么 ps.setString()不起作用。。数据库是 mysql
|
2
SuperMild 2017-11-28 15:07:25 +08:00 1
rs.next()执行了两次
|
3
Hzzone 2017-11-28 15:09:08 +08:00
rs.next()执行了两次
|
4
choice4 OP 哇感谢感谢 糗了 不过控制台输出 syso(sb)为什么里边还是问号啊 我以前看视频跟着打的时候当传进参数输出问号就会被赋值输出来啊?这个咋回事
|
5
tianshuang 2017-11-28 15:15:04 +08:00
这代码块,还是用 Java 7+ 支持 auto close 的 try catch 吧。
|
6
choice4 OP 这是对比的那个
List<Goddess> result = new ArrayList<Goddess>(); Connection conn = DBUtil.getConnection(); StringBuilder sb = new StringBuilder(); sb.append(" select * from imooc_goddess where 1=1 "); if (params != null && params.size() > 0) { for (int i = 0; i < params.size(); i++) { Map<String, Object> map = params.get(i); sb.append(" and" + " " + map.get("name") + " " + map.get("rela") + " " + map.get("value")); } } PreparedStatement ptmt = conn.prepareStatement(sb.toString()); System.out.println(sb.toString()); 主函数里是 List<Map<String, Object>> params = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "user_name"); map.put("rela", "="); map.put("value", "'木冰眉'"); params.add(map); List<Goddess> result = action.query(params); for (int i = 0; i < result.size(); i++) { System.out.println(result.get(i).getId() + ":" + result.get(i).getUser_name() + result.get(i).getBirthday()); } /** * 控制台打印 * select * from imooc_goddess where 1=1 and user_name = '木冰眉' *2:木冰眉 2000-05-02 */ |
7
choice4 OP 对。。myeclipse 里自带的 jdk 懒得弄了。。
|
9
choice4 OP 哇 难了半天来 v2 秒解 感谢大佬感谢大佬
|