DBUtil实战
問題:設計一個簡單的學生操作系統,實現功能要求如下
package jdbc;import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner;import org.omg.Messaging.SyncScopeHelper;import com.jd.util.DBUtil; import com.jd.util.IRowMapper;public class Main {public static void main(String[] args) {System.out.println("*********************************");System.out.println("*\t\t\t\t*");System.out.println("*\t歡迎使用學生信息管理系統\t*");System.out.println("*\t\t\t\t*");System.out.println("*********************************");while (true) {menu();}}public static void menu() {System.out.println("1、添加學生信息");System.out.println("2、刪除學生信息");System.out.println("3、修改學生信息");System.out.println("4、查詢學生信息");System.out.println("請輸入操作,以Enter鍵結束:");Scanner scanner = new Scanner(System.in);int option = scanner.nextInt();class RowMapper implements IRowMapper {@Overridepublic void rowMapper(ResultSet resultSet) {try {while (resultSet.next()) {String id = resultSet.getString("id");String name = resultSet.getString("name");System.out.println(id);System.out.println(name);}} catch (SQLException e) {e.printStackTrace();}}}switch (option) {case 1:{System.out.println("請輸入需要添加的學生學號");String id=scanner.next();if(DBUtil.exist("select *from student where id=?",id)) {System.out.println("該學號已存在");}else {System.out.println("請輸入學生的姓名");String name=scanner.next();DBUtil.update("insert into student (id,name) VALUES (?,?)",id,name);System.out.println("添加成功");}break;}case 2:{System.out.println("請輸入需要刪除的學生學號");String id=scanner.next();if(DBUtil.exist("select *from student where id=?",id)) {DBUtil.update("delete from student where id=?",id);System.out.println("刪除成功");}else {System.out.println("該學號不存在");}break;}case 3:{System.out.println("請輸入需要修改的學生學號");String id=scanner.next();if(DBUtil.exist("select *from student where id=?",id)) {System.out.println("請輸入學生的姓名");String name=scanner.next();DBUtil.update("update student set name=? where id=?", name,id);System.out.println("修改成功");}else {System.out.println("該學號不存在");}break;}case 4:{System.out.println("請輸入需要查詢的學生學號");String id=scanner.next();if(DBUtil.exist("select *from student where id=?",id)) {RowMapper rowMapper = new RowMapper();DBUtil.select("select * from student where id=?",rowMapper,id);}else {System.out.println("該學號不存在");}break;}default:System.out.println("請輸入正確的選項");}} }在這里我們寫的main方法其實只是一個界面而已,真正管理了學生信息使用的是之前的DBUtil工具類,而DBUtil工具類中的方法由menu方法(管理系統的菜單)來進行調用,通過給menu套上一個死循環來使得其可立即重復執行。
總結
- 上一篇: Linq动态查询与模糊查询
- 下一篇: iOS回顾笔记( 02 ) -- 由九宫