第15周作业--JDBC连接数据库
编写一个应用程序,输入用户名和密码,访问test数据库中t_login表(字段包括id、username、password),验证登录是否成功。当登录成功后,将t_user表(id、name、sex、birthday)的信息进行显示(要求使用DB.java完成登录和获取t_user表中数据的操作),最后再对t_user表进行一条记录的添加操作。
package com; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class Test2 { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.println("请输入用户名"); String uesrname = reader.next(); System.out.println("密码"); String password = reader.next(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", ""); String sql = "select * from t_login where username=? and password=?"; String sql2 = "select * from t_user"; String sql3 = "insert into t_user(name,sex,birthday) values(?,?,?)"; ps = con.prepareStatement(sql); ps.setString(1, uesrname); ps.setString(2, password); rs = ps.executeQuery(); if (rs.next()) { System.out.println("登录成功!"); } else { System.out.println("登录失败!"); } rs = ps.executeQuery(sql2); System.out.println(""); System.out.println("显示所有成员信息:"); while (rs.next()) { String name = rs.getString(2); System.out.println("name :" + name); int sex = rs.getInt(3); if (sex == 1) { System.out.println("sex :男"); } else { System.out.println("sex :女"); } String birthday = rs.getString(4); System.out.println("birthday:" + birthday); } ps = con.prepareStatement(sql3); System.out.println("请输入姓名:"); String name = reader.next(); ps.setString(1, name); System.out.println("请输入性别,1代表男,2代表女"); int sex = reader.nextInt(); ps.setInt(2, sex); System.out.println("请输入出生日期:"); String birthday = reader.next(); ps.setString(3, birthday); int count = ps.executeUpdate(); if (count > 0) { System.out.println("插入成功"); } else { System.out.println("插入失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }