概述
在Java学习过程中,将学到的知识综合到一起使用是一个必要的过程,今天,在朋友的邀请下,针对Java刚学习完,还不知道如何综合使用的情况下写的一篇笔记。
新建的项目采用的是MVC模式构建的,使用的eclipse + mysql5.6.12 + jdk1.8.0_71, 针对学生信息的增删改查开发的一个简单的管理系统(无界面)
MVC是什么?
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
如同,我们新建个项目,新建几个包将功能区分开来
分别说下每个包的作用:
名称 作用
Control 用于存放操作数据的类,在View和数据库中间起着连接的作用
Dao 用于存放操作数据库数据的类
Db 用于得到数据库连接
Model 用于存放项目中需要用到的模型的实体类
View 用于存放视图(界面)的类(此时用控制台表示)
开发过程
建好包之后,我们开始添加代码,首先,我们分析下整个demo该怎么进行:
我们的目的是为了从数据库中交互数据,
第一步应该是建表:
这里,我们只针对学生信息进行操作,所以此处应该只需要新建一张表(Student):
create database myschool character set utf8;create table students(_id int unsigned not null auto_increment primary key,name varchar(20) not null,sex varchar(5) not null,age int not null,phone varchar(11) not null,address varchar(20) not null);use myschool;insert into students values(\'\',\'老肖\',\'男\',22,\'13872425061\',\'湖北荆州\');
表新建完成后,
第二步我们开始去写Java代码:
1、使用mysql-connector-java-5.1.7-bin.jar连接工具连接MySQL数据库:
在Db中新建DbConnection类
/*** 用于得到数据库的连接* @author Auser* 导入的是这个 import com.mysql.jdbc.Connection*/public class DbConnection {private static Connection coon=null;static{try {//1、加载驱动程序Class.forName(\"com.mysql.jdbc.Driver\");//2、获得数据库的链接String connstr = \"jdbc:mysql://localhost:3306/myschool?user=root&password=123456&useUnicode=true&characterEncoding=utf-8\";coon = (Connection) DriverManager.getConnection(connstr);System.out.println(\"连接成功\");} catch (ClassNotFoundException e) {e.printStackTrace();System.out.println(\"连接失败\");} catch (SQLException e){e.printStackTrace();System.out.println(\"连接失败\");}}public static Connection getConnection(){return coon;}}
我们在View中新建MainView类来测试下是否可以连接成功。
public class MainView {public static void main(String[] args) {Connection connection = DbConnection.getConnection();}}
点击运行:
我们测试连接成功后,需要在Dao包里面去新建一个StudentDao类,写入增删改查四个方法开始操作数据库的数据,但是在这之前,我们需要去找到我们要操作的模型(Model),在这个demo中,我们操作的是学生这个对象,所以,我们Model包中需要去新建一个学生的实体类(Student):
public class Student {private int id;private String name;private String sex;private int age;private String phone;private String address;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public Student(String name, String sex, int age, String phone, String address) {super();this.name = name;this.sex = sex;this.age = age;this.phone = phone;this.address = address;}public Student() {}@Overridepublic String toString() {return \"Student [id=\" + id + \", name=\" + name + \", sex=\" + sex + \", age=\" + age + \", phone=\" + phone+ \", address=\" + address + \"]\";}}
2、数据库操作之查找
public static List<Student> QueryAllStudents(Connection connection) {Statement stt = null;ResultSet rs = null;List<Student> students = new ArrayList<>();try {stt = (Statement) connection.createStatement();rs=stt.executeQuery(\"select * from students\");while(rs.next()){int id = rs.getInt(\"_id\");String name = rs.getString(\"name\");String sex = rs.getString(\"sex\");int age = rs.getInt(\"age\");String phone = rs.getString(\"phone\");String address = rs.getString(\"address\");Student student = new Student(name,sex,age,phone,address);students.add(student);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println(\"查询失败\");}finally{try {stt.close();rs.close();connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return students;}
在Control中新建StudentInforControl类去操作得到的数据
public static String getAllStudentInfor(){Connection connection = DbConnection.getConnection();List<Student> students = StudentDao.QueryAllStudents(connection);if(students.size() != 0){StringBuffer buffer = new StringBuffer();for (int i = 0; i < students.size(); i++) {buffer.append(students.get(i).toString()+\"\\n\");}return buffer.toString();}else{return \"数据库为空\";}}
在MainView中调用该方法:
public static void main(String[] args) {String result = StudentInforControl.getAllStudentInfor();System.out.println(result);}
3、数据库操作之增加
public static boolean AddStudentInfor(Connection connection, Student student) {boolean result;String mysql = \"insert into students(name,sex,age,phone,address) values(?,?,?,?,?)\";PreparedStatement ptt = null;try {ptt = (PreparedStatement) connection.prepareStatement(mysql);ptt.setString(1, student.getName());ptt.setString(2, student.getSex());ptt.setInt(3, student.getAge());ptt.setString(4, student.getPhone());ptt.setString(5, student.getAddress());ptt.execute();result = true;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();result = false;}finally {try {ptt.close();connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return result;}
同理,在StudentInforControl类中去操作得到的数据
public static String InsertStudent(Student student){Connection connection = DbConnection.getConnection();boolean result= StudentDao.AddStudentInfor(connection, student);if (result) {return \"添加成功\";}else{return \"添加失败\";}}
在MainView中调用该方法:
public static void main(String[] args) {Student student = new Student(\"老王\",\"男\",34,\"13177020905\",\"湖北武汉\");String result = StudentInforControl.InsertStudent(student);System.out.println(result);}
4、数据库操作之删除
public static boolean DeleteStudentInfor(Connection connection, int _id) {boolean result;String sql=\"delete from students where _id=?\";PreparedStatement pst = null;try {pst = (PreparedStatement) connection.prepareStatement(sql);pst.setInt(1, _id);pst.execute();result = true;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();result = false;} finally {try {pst.close();connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return result;}
同理,在StudentInforControl类中去操作得到的数据
public static String DeleteStudent(int _id){Connection connection = DbConnection.getConnection();boolean result= StudentDao.DeleteStudentInfor(connection, _id);if (result) {return \"删除成功\";}else{return \"删除失败\";}}
在MainView中调用该方法:
public static void main(String[] args) {String result = StudentInforControl.DeleteStudent(1);System.out.println(result);}
5、数据库操作之更新(修改)
public static boolean UpdateStudentInfor(Connection connection, Student student) {boolean result;String sql=\"update students set name=?,sex=?,age=?,phone=?,address=? where _id = ?\";PreparedStatement pst = null;try {pst=(PreparedStatement) connection.prepareStatement(sql);pst.setString(1, student.getName());pst.setString(2, student.getSex());pst.setInt(3, student.getAge());pst.setString(4, student.getPhone());pst.setString(5, student.getAddress());pst.setInt(6, student.getId());pst.execute();result = true;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();result = false;} finally {try {pst.close();connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return result;}
同理,在StudentInforControl类中去操作得到的数据
public static String UpdateStudent(Student student){Connection connection = DbConnection.getConnection();boolean result= StudentDao.UpdateStudentInfor(connection, student);if (result) {return \"修改成功\";}else{return \"修改失败\";}}
在MainView中调用该方法:
public static void main(String[] args) {Student student = new Student(\"老王\",\"男\",18,\"13131313133\",\"湖南长沙\");student.setId(4);String result = StudentInforControl.UpdateStudent(student);System.out.println(result);}