首页 > 代码库 > JAVA使用JDBC连接MySQL数据库(3)-代码部分

JAVA使用JDBC连接MySQL数据库(3)-代码部分

 1     /**************连接数据库部分********************/
 2     public static Connection conn(){
 3         Connection conn = null;
 4         String driver = "com.mysql.jdbc.Driver";
 5         String url = "jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8";
 6         String username="root";
 7         String pw = "111111";
 8         
 9         try {
10             Class.forName(driver);//指定连接类型 
11             System.out.println("成功加载驱动程序!!!!");
12             conn = (Connection) DriverManager.getConnection(url,username,pw);//获取连接
13         } catch (Exception e) {
14             // TODO: handle exception
15             e.printStackTrace();
16         }
17         return conn;
18     }
 1     /**************操作部分********************/
 2     //管理员登录
 3     public boolean checkAdmin(Admin admin){
 4         Connection conn = conn();
 5         String sql = "select * from user where username = ? and userpass= ? ";//SQL语句 
 6         PreparedStatement pstmt = null;
 7         ResultSet rs = null;
 8         boolean bl = false;
 9         try{
10             pstmt = (PreparedStatement) conn.prepareStatement(sql);
11             pstmt.setString(1, admin.getAdminname()); //问号1
12             pstmt.setString(2,admin.getAdminpassword()); //问号2
13             rs = pstmt.executeQuery();  //结果集
14             if(rs.next()){
15                 System.out.println("登录成功");
16                 bl = true;
17             }else{
18                 System.out.println("用户名或密码错误");                    
19             }
20             rs.close();
21             pstmt.close();
22             conn.close(); //关闭连接
23         }catch(SQLException e){
24             e.getStackTrace();
25         }
26         return bl;
27     }
 1 package com.entity;
 2 
 3 public class Admin {
 4     private String adminname;
 5     private String adminpassword;
 6     
 7     public Admin(String adminname,String adminpassword){
 8         this.adminname = adminname;
 9         this.adminpassword = adminpassword;
10     }
11     
12     //管理员名字
13     public String getAdminname() {
14         return adminname;
15     }
16     public void setAdminname(String adminname) {
17         this.adminname = adminname;
18     }
19     
20     //管理员密码
21     public String getAdminpassword(){
22         return adminpassword;
23     }
24     public void setAdminpassword(String adminpassword){
25         this.adminpassword = adminpassword;
26     }
27 }
 1     /***********测试******************/
 2     public static void main(String[] args){
 3         Connsql sql = new Connsql();
 4         Admin admin = new Admin("amin","111111");
 5         boolean bl = sql.checkAdmin(admin);
 6         if(bl){
 7             System.out.println("ok");
 8         }else{
 9             System.out.println("wrong");
10         }
11     }

 

JAVA使用JDBC连接MySQL数据库(3)-代码部分