今天整理查询的方法。
一、代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
package dao; import java.sql.ResultSet; import java.util.Date; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import jdbc.dbconnection; public class search { public static String id = "3"; public void search() throws Exception { Connection conn = dbconnection.getConnection(); String sql = " select * from myfriend where id = ? "; PreparedStatement ptmt = (PreparedStatement) conn.prepareStatement(sql); ptmt.setString(1,id); try{ ResultSet rs = ptmt.executeQuery(); while(rs.next()) { int id = rs.getInt("id"); String user_name = rs.getString("user_name"); int age = rs.getInt("age"); int sex = rs.getInt("sex"); Date birthday = rs.getDate("birthday"); String email = rs.getString("email"); String mobile = rs.getString("mobile"); Date create_date = rs.getDate("create_date"); String create_user = rs.getString("create_user"); Date update_date = rs.getDate("update_date"); String update_user = rs.getString("update_user"); int isdel = rs.getInt("isdel"); System.out.println("search success"); System.out.println(id+" "+user_name+" "+age+" "+sex+" "+birthday+" "+email); System.out.println(mobile+" "+create_date+" "+create_user+" "+update_date+" "+update_user+" "+isdel); } }catch(Exception e) { e.printStackTrace(); System.out.println("search fail"); System.out.println(sql); } } public static void main(String[] args) throws Exception { search s = new search(); s.search(); } } |
需要注意的是:
首先,要创建的对象一定是preparestatement,因为只有preparestatement有executeQuery方法,才能执行sql语句。
之后,我们需要创建一个结果集:
1 |
ResultSet rs = ptmt.executeQuery(); |
然后通过:
1 2 |
int id = rs.getInt("id"); String user_name = rs.getString("user_name"); |
取得查询的值(结果集的映射),最后再syso输出。
二、总结
记录一下。