package songyan.jdbc.crud;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import songyan.jdbc.util.DBUtil;
import songyan.jdbc.entity.*;

 
 public class CRUD_prepared{
     
     public static void selectTest() throws Exception
     {
         Connection conn=null;
         PreparedStatement sta=null;
         ResultSet rs=null;
         String sql="select * from users where name=? and password=?";
         
         conn=DBUtil.getConnection();
         
         sta=conn.prepareStatement(sql);
         sta.setString(1, "zhansan");
         sta.setString(2, "123");
         
         rs=sta.executeQuery();
         
         List<User> l= new ArrayList<User>();         
         while(rs.next())
         {
            User u= new User();
            u.setId(rs.getInt("id"));
            u.setName(rs.getString("name"));
            u.setPassword(rs.getString("password"));
            u.setEmail(rs.getString("email"));
            u.setBirthday(rs.getDate("birthday"));
            l.add(u);
         }
         
         for(User u:l)
         {
             System.out.println(u.getId()+" "+u.getName());
         }
         
         DBUtil.closeAll(conn, sta, rs);
         
     }
     
     public static void insertTest() throws SQLException
     {
         Connection conn=null;
         PreparedStatement sta=null;
         ResultSet rs=null;
         String sql="insert into users values(1,'a0','b0','a@163.com','1981-12-04')";
         
         conn=DBUtil.getConnection();
         
         sta=conn.prepareStatement(sql);

         System.out.println(sta.executeUpdate());        
         
         DBUtil.closeAll(conn, sta, rs);
     }
     
     public static void updateTest() throws SQLException
     {
         Connection conn=null;
         PreparedStatement sta=null;
         ResultSet rs=null;
         String sql="update users set name='lisi' where id='4'";
         conn=DBUtil.getConnection();
         
         sta=conn.prepareStatement(sql);
         
         System.out.println("影响了"+sta.executeUpdate());        
         
         DBUtil.closeAll(conn, sta, rs);
     }
     
     public static void deleteTest() throws SQLException
     {
         Connection conn=null;
         PreparedStatement sta=null;
         ResultSet rs=null;
         String sql="delete from users where name='bbb'";
         
         conn=DBUtil.getConnection();
         
         sta=conn.prepareStatement(sql);
         System.out.println(sta.executeUpdate());        
         
         DBUtil.closeAll(conn, sta, rs);
     }
     
     public static void main(String[] args) throws Exception
     {
         deleteTest();
     }
 }

 

posted on 2018-03-11 21:00  song.yan  阅读(190)  评论(0编辑  收藏  举报