Topic 1: write an application, a user name and password to access the test database t_login table (field, including id, username, password), to verify whether the login was successful.
Problem 2: On the basis of a title, if the login is successful, the table t_user information (id, name, sex, birthday) for display (DB.java required to complete the sign and data acquisition operations t_user table), and finally t_user table again add a record operation.
Code:
DB class
package ccut; import java.sql.*; public class DB { private Connection con; private PreparedStatement pre; private ResultSet rs; private static DB test; static{ try{ Class.forName("com.mysql.jdbc.Driver"); }catch(ClassNotFoundException e){ e.printStackTrace(); } } DB(){ try{ con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root",""); }catch(SQLException e){ e.printStackTrace(); } } public static DB getInstabce(){ if(test==null){ test=new DB(); } return test; } public ResultSet executeSelect(String sql,Object[] args){ try{ pre=con.prepareStatement(sql); if(args.length!=0){ for(int i=0;i<args.length;i++){ pre.setObject(i+1, args[i]); } } rs = pre.executeQuery(); }catch(SQLException e){ e.printStackTrace(); } return rs; } public int executeModify(String sql,Object[] args){ int n=0; try{ pre=con.prepareStatement(sql); if(args.length!=0){ for(int i=0;i<args.length;i++){ pre.setObject(i+1, args[i]); } } n = pre.executeUpdate(); }catch(SQLException e){ e.printStackTrace(); } return n; } public void close(){ try{ if(rs!=null){ rs.close(); } pre.close(); con.close(); }catch(SQLException e){ e.printStackTrace(); } } }
test category
package ccut; import java.util.*; import java.sql.*; public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入账号和密码:"); Scanner input=new Scanner(System.in); String username=input.next(); String password=input.next(); ResultSet a; ResultSet b; DB db = new DB(); a = db.executeSelect("select * from t_login where username = '"+username+"' and password = '"+password+"'", args); try { if (a.next()) { System.out.println("登录成功"); System.out.println("以下为t_user表中的信息:"); b = db.executeSelect("select * from t_user", args); while(b.next()) { int id = b.getInt (1 ); String name= b.getString(2); int sex = b.getInt(3); String birthday = b.getString(4); System.out.println("id:"+id+"\tname:"+name+"\tsex:"+sex+"\tbirthday:"+birthday); } System.out.println("请输入插入信息:"); int id1 = input.nextInt(); String name1 = input.next(); int sex1 = input.nextInt(); String date1 = input.next(); String sql="insert into t_user(id,name,sex,birthday) values("+id1+",'"+name1+"',"+sex1+",'"+date1+"')"; int n = db.executeModify(sql, args); if(n>0) { System.out.println("插入成功"); }else { System.out.println("插入失败"); } }else { System.out.println("登陆失败"); } } catch(An SQLException e) { e.printStackTrace (); } } }
Screenshot