创建项目,导入数据库驱动程序,帮助文档,图片创建实体类College,Status,Student,User对应学校表,状态表,学生表,用户表。创建实体类ConnectionManager连接数据库。创建DisplayAllUsers,FindUserByld测试数据库操作
help文件夹存放帮助文档,images文件夹存放图片,lib文件夹存放数据库驱动程序
college类: status类:
student类:
user类:
创建这四个类可以使用快捷方法alt+inster选择方法getter setter, toString()快速生成代码,在这里只将类属性列出。
在这里需要注意数据库四个属性不要写错根据自己电脑上的数据库密码,用户名已经自己导入的数据库驱动程序来写
DisplayAllUsers类: 查询出用户表中的所有数据并在控制台输出
package net.yw.student.test; import net.yw.student.bean.User; import net.yw.student.dbutil.ConnectionManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DisplayAllUsers { public static void main(String[] args) { Connection conn = ConnectionManager.getConnection(); String strSQL = "select * from t_user"; try { //这里需要加上异常处理否则会报错,同下 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(strSQL); while (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setTelephone(rs.getString("telephone")); user.setRegisterTime(rs.getTimestamp("register_time")); System.out.println(user); } }catch (SQLException throwables) { throwables.printStackTrace(); } finally { ConnectionManager.closeConnection(conn); } } }FindUserByld类: 根据id查找用户
package net.yw.student.test; import net.yw.student.dbutil.ConnectionManager; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; public class FindUserByld { public static void main(String[] args) { int id; Scanner sc = new Scanner(System.in); System.out.print("请输入待查用户编号:"); id=sc.nextInt(); Connection conn = ConnectionManager.getConnection(); try { String strSQL = "select * from t_user where id = ?"; PreparedStatement psmt = conn.prepareStatement(strSQL); psmt.setInt(1, id); ResultSet rs = psmt.executeQuery(); if(rs.next()){ System.out.println("编号:"+rs.getInt("id")); System.out.println("用户名:"+rs.getString("username")); System.out.println("密码:"+rs.getString("password")); System.out.println("电话:"+rs.getString("telephone")); System.out.println("注册时间:"+rs.getTimestamp("register_time")); }else { System.out.println("查询用户不存在!"); } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(conn); } } }