- 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 Jdbc {
- public static void main(String[] args) throws SQLException {
- PreparedStatement pst = null;
- ResultSet rs = null;
- Scanner sin = new Scanner(System.in);
- boolean flag = true;
- // 数据库连接
- Connection conn = null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- conn = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/jdbc", "root", "123456");
- } catch (SQLException | ClassNotFoundException e1) {
- e1.printStackTrace();
- }
- // 数据库操作
- System.out.println("=================================");
- System.out.println(" 0 结束 1 查询(女) 2 查询(男) 3 添加 4 删除 ");
- System.out.println("=================================");
- while (flag) {
- System.out.println("请输入操作序号");
- switch (sin.next()) {
- case "0":
- flag = false;
- break;
- case "1":
- try {
- pst = conn
- .prepareStatement("select * from t_user where sex='女'");
- rs = pst.executeQuery();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if(rs != null) {
- while (rs.next()) {
- String str = "ID:" + rs.getString(1) + " 姓名:" + rs.getString(2)
- + " 性别:" + rs.getString(3);
- System.out.println(str);
- }
- }
- break;
- case "2":
- try {
- pst = conn
- .prepareStatement("select * from t_user where sex='男'");
- rs = pst.executeQuery();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if(rs != null) {
- while (rs.next()) {
- String str = "ID:" + rs.getString(1) + " 姓名:" + rs.getString(2)
- + " 性别:" + rs.getString(3);
- System.out.println(str);
- }
- }
- break;
- case "4":
- System.out.println("请输入学号:");
- try {
- pst = conn
- .prepareStatement("delete from t_user where id=?");
- pst.setInt(1, Integer.valueOf(sin.next()));
- int result = pst.executeUpdate();
- if(result != 0) {
- System.out.println("删除成功!");
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if(rs != null) {
- while (rs.next()) {
- String str = "ID:" + rs.getString(1) + " 姓名:" + rs.getString(2)
- + " 性别:" + rs.getString(3);
- System.out.println(str);
- }
- }
- break;
- case "3":
- try {
- pst = conn
- .prepareStatement("insert t_user(id,name,sex) values(?,?,?)");
- System.out.println("请输入学号:");
- pst.setInt(1,Integer.valueOf(sin.next()));
- System.out.println("请输入姓名:");
- pst.setString(2,sin.next());
- System.out.println("请输入性别:");
- pst.setString(3,sin.next());
- int result = pst.executeUpdate();
- if(result != 0) {
- System.out.println("增加成功!");
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if(rs != null) {
- while (rs.next()) {
- String str = "ID:" + rs.getString(1) + " 姓名:" + rs.getString(2)
- + " 性别:" + rs.getString(3);
- System.out.println(str);
- }
- }
- break;
- default:
- System.out.println("输入无效,请重新输入!");
- }
- }
-
- conn.close();
- pst.close();
- rs.close();
- sin.close();
- }
- }
复制代码
上面是我的代码,你看下是否有需要改的地方。上面的代码运行没有问题,如果可以的话,可以继续讨论。
谢谢,{:3_57:} |