题目1:编写一个应用程序,输入用户名和密码,访问test数据库中t_login表(字段包括id、username、password),验证登录是否成功。
题目2:在上一题基础上,当登录成功后,将t_user表(id、name、sex、birthday)的信息进行显示(要求使用DB.java完成登录和获取t_user表中数据的操作),最后再对t_user表进行一条记录的添加操作。
代码:
package Example12_11; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; import Example12_12.DB; public class Test12_12 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner reader = new Scanner(System.in); String x = reader.next(); String y = reader.next(); ResultSet verify; //验证username password是否正确 ResultSet query; //查询t_user表中内容 DB db = new DB(); verify = db.executeSelect("select * from t_login where username = '"+x+"' and password = '"+y+"'", args); //验证账户密码 try { if (verify.next()) { System.out.println("登录成功"); System.out.println("t_user表中的信息"); query = db.executeSelect("select * from t_user", args); //获取t_user表中信息 while(query.next()) { int id = query.getInt(1); String name = query.getString(2); int sex = query.getInt(3); String birthday = query.getString(4); System.out.println("id:"+id+" name:"+name+" sex:"+sex+" birthday:"+birthday); } System.out.println("请输入需要添加的记录:"); int newid = reader.nextInt(); String newname = reader.next(); int newsex = reader.nextInt(); String newdate = reader.next(); String sql="insert into t_user(id,name,sex,birthday) values("+newid+",'"+newname+"',"+newsex+",'"+newdate+"')"; //记录添加操作 int n = db.executeModify(sql, args); if(n>0) { System.out.println("数据插入成功"); }else { System.out.println("数据插入失败"); } }else { System.out.println("登陆失败"); } } catch (SQLException e) { e.printStackTrace(); } } }
DB.java代码:
package Example12_12; import java.sql.*; public class DB { private Connection con; private PreparedStatement pre; private ResultSet rs; private static DB db; static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public DB() { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase?useSSL=false&serverTimezone=UTC","root","1234"); } catch (SQLException e) { e.printStackTrace(); } } public static DB getInstance() { if(db == null) { db = new DB(); } return db; } 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(); } } }
运行截图:
验证登录,成功后将t_user表信息进行显示:
数据库t_login表中内容: 数据库t_user表中内容
对t_user表进行一条记录添加:
添加后数据库t_user表中内容: