jdbc 链接数据库
创建一个user类是要与数据库的属性一致作为

java类必须和mysql对应上

创建 Bean包
创建user类
package Dao.bean; import java.io.Serializable; public class User implements Serializable{ private int id;//用户名编号 private String userName;//用户名 private String loginName;//登录名 private String password;//密码 private int sex;//用户的性别 private String identityCode;//用户身份证号 private String email;//用户邮箱 private String mobile;//用户手机号 private int type;//用户的类型1管理员 0普通用户 public User() { super(); } public String toString() { return "User [id=" + id + ", userName=" + userName + ", loginName=" + loginName + ", password=" + password + ", sex=" + sex + ", identityCode=" + identityCode + ", email=" + email + ", mobile=" + mobile + ", type=" + type + "]"; } public User(int id, String userName, String loginName, String password, int sex, String identityCode, String email, String mobile, int type) { super(); this.id = id; this.userName = userName; this.loginName = loginName; this.password = password; this.sex = sex; this.identityCode = identityCode; this.email = email; this.mobile = mobile; this.type = type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getIdentityCode() { return identityCode; } public void setIdentityCode(String identityCode) { this.identityCode = identityCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
创建News类
package Dao.bean; import java.io.Serializable; import java.util.Date; public class News implements Serializable{ private int id;//新闻编号 private String title;//新闻标题 private String content;//新闻内容 private Date createTime;//创建时间 private String img;//新闻的图片 @Override public String toString() { return "News [id=" + id + ", title=" + title + ", content=" + content + ", createTime=" + createTime + ", img=" + img + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public News(int id, String title, String content, Date createTime, String img) { super(); this.id = id; this.title = title; this.content = content; this.createTime = createTime; this.img = img; } public News() { super(); } }
创建一个dao层包
创建一个UserDao接口
package Dao.dao;
import java.io.Serializable;
import java.util.List;
import Dao.bean.User;
/**
*
* 用户的增删改查
*
*/
public interface UserDao extends BaseDao<User>{
User login(String loginName,String password);
}
创建一个NewsDao接口
package Dao.dao;
import java.io.Serializable;
import java.util.List;
import Dao.bean.News;
import Dao.bean.User;
public interface NewsDao extends BaseDao<News> {
}
创建一个BaseDao接口
让 UserDao 和 NewsDao 实现 BaseDao
package Dao.dao;
import java.io.Serializable;
import java.util.List;
import Dao.bean.News;
import Dao.bean.User;
public interface BaseDao<T> {
int add(T t);
int delete(Serializable id);
int update(T t);
List<T> findAll();
T findById(Serializable id);
}
创建impl包
和创建Userimpl类
package Dao.impl; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import Dao.bean.User; import Dao.dao.UserDao; import Dao.util.JdbcUtil; import Dao.util.ResultSetUtil; public class UserDaoImpl extends JdbcUtil implements UserDao { /** * 登录 */ @Override public User login(String loginName, String password) { String sql = "select * from easybuy_user where loginName=? and password=?"; // 给参数赋值 Object[] params = { loginName, password }; User user = null; try { rs = myExcuteQuery(sql, params); user = ResultSetUtil.findById(rs, User.class); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { closeConnection(); } return user; } /** * 现在网址注册 一般都是 用户名 密码 +邮箱/手机号 * 之后用户的详细信息 可以进行完善 */ @Override public int add(User t) { String sql = "insert into easybuy_user(userName,loginName,password,sex,identityCode,email,mobile,type) values(?,?,?,?,?,?,?,?)"; Object[] params = { t.getUserName(), t.getLoginName(), t.getPassword(), t.getSex(), t.getIdentityCode(), t.getEmail(), t.getMobile(), t.getType() }; int rowNum = 0; try { rowNum = myExcuteUpdate(sql, params); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return rowNum; } /** * 因为用户有可能根据id删除对象,也有可能是根据其他的选择! * 我们不确定类型,所以就把参数类型设置为Serializable * * 遗留问题? * id为空 根据name删除 * name为空 根据id删除 */ @Override public int delete(Serializable id) { String sql = "delete from easybuy_user where id=?"; Object[] params = { id }; int rowNum = 0; try { rowNum = myExcuteUpdate(sql, params); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return rowNum; } /** * 修改 * 我们怎么知道用户到底修改了什么? */ @Override public int update(User t) { String sql = "update easybuy_user set loginName=?,password=? where id=?"; Object[] params = { t.getLoginName(), t.getPassword(), t.getId() }; int rowNum = 0; try { rowNum = myExcuteUpdate(sql, params); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return rowNum; } @Override public List<User> findAll() { String sql = "select * from easybuy_user"; // 创建一个集合来保存所有的用户 List<User> users = new ArrayList<>(); try { rs = myExcuteQuery(sql); users = ResultSetUtil.findAll(rs, User.class); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { closeConnection(); } return users; } /** * 查询指定的用户信息 */ @Override public User findById(Serializable userID) { String sql = "select * from easybuy_user where id=?"; // 给参数赋值 Object[] params = { userID }; User user = null; try { rs = myExcuteQuery(sql, params); user = ResultSetUtil.findById(rs, User.class); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { closeConnection(); } return user; } }
创建Nwesimpl类
package Dao.impl; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import Dao.bean.News; import Dao.bean.News; import Dao.bean.detail; import Dao.bean.order; import Dao.dao.NewsDao; import Dao.dao.NewsDao; import Dao.util.JdbcUtil; import Dao.util.ResultSetUtil; public class NewsDaoImp extends JdbcUtil implements NewsDao{ public int add(News t) { String sql="insert into easybuy_News(title,content,createTime,img) values(?,?,?,?)"; Object[] param={t.getTitle(),t.getContent(),t.getCreateTime(),t.getImg()}; int rowNum=0; try { rowNum=myExcuteUpdate(sql, param); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeConnection(); } return rowNum; } //删除 public int delete(Serializable id) { String sql="delete from easybuy_News where id=?"; Object[]params={id}; try { myExcuteUpdate(sql,params); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeConnection(); } return 0; } //修改 public int update(News t) { String sql="update easybuy_News set title='?',content='?' where id=?"; Object[] params={t.getTitle(),t.getContent(),t.getId()}; int rowNum=0; try { rowNum=myExcuteUpdate(sql, params); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeConnection(); } return rowNum; } //查询 public List<News> findAll() { String sql="select* from easybuy_News"; List<News> Newss=new ArrayList<>(); try { rs=myExcuteQuery(sql); Newss=ResultSetUtil.findAll(rs,News.class); // while(rs.next()){ // int id=rs.getInt("id"); // String title=rs.getString("title"); // String content=rs.getString("content"); // Date createTime=rs.getTimestamp("createTime"); // String img=rs.getString("img"); // News News=new News(id,title,content,createTime,img); // Newss.add(News); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeConnection(); } return Newss; } //登录 public News login(String loginName, String password) { String sql="select *from easybuy_News where loginName=? and password=?"; News News=null; Object[] params={loginName,password}; try { rs=myExcuteQuery(sql, params); News=ResultSetUtil.findById(rs, News.class); // if(rs.next()){ // int id=rs.getInt("id"); // String title=rs.getString("title"); // String content=rs.getString("content"); // Date createTime=rs.getTimestamp("createTime"); // String img=rs.getString("img"); // News=new News(id, title, content, createTime, img); // } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeConnection(); } return News; } public News findById(Serializable id) { String sql = "select * from easybuy_user where id=?"; // 给参数赋值 Object[] params = { id }; News news = null; try { rs = myExcuteQuery(sql, params); news = ResultSetUtil.findById(rs, News.class); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { closeConnection(); } return news; } }
创建serverce包
创建BaseServiceService接口
package Dao.serverce;
import java.io.Serializable;
import java.util.List;
import Dao.bean.User;
public interface BaseService{
}
创建serverce包
创建NewsService接口
package Dao.serverce; import Dao.bean.News; public interface NewsService { }
创建serverce包
创建UserService接口
package Dao.serverce;
import java.io.Serializable;
import java.util.List;
import Dao.bean.User;
public interface UserService {
User login(String loginName, String password);
/**
* 新增
*/
void add(User t);
/**
* 删除
*/
void delete(Serializable id);
/**
* 修改
*/
void update(User t);
/**
* 查询所有
*/
List<User> findAll();
/**
* 指定查询
*/
User findById(Serializable id);
}
创建DaoServic包
创建Userimpl类
package Dao.servic.imp;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import org.apache.poi.util.SystemOutLogger;
import utilclass.UtilClass;
import com.sun.istack.internal.logging.Logger;
import Dao.bean.News;
import Dao.bean.User;
import Dao.dao.UserDao;
import Dao.impl.UserDaoImpl;
import Dao.serverce.NewsService;
import Dao.serverce.UserService;
import Dao.util.JdbcUtil;
import Dao.util.MemcachedUtil;
public class UserImpServic implements UserService{
// 实例化dao层对象 但是这种方式不可取 是耦合的!
UserDao dao = new UserDaoImpl();
private static Logger logger= Logger.getLogger(UserImpServic.class);
/**
* 登录
*/
@Override
public User login(String loginName, String password) {
User user = dao.login(loginName, password);
if (user == null) {
logger.info("登录失败");
return null;
} else {
logger.info("用户登录成功!");
return user;
}
}
public void add(User t) {
int rowNum = dao.add(t);
if (rowNum > 0) {
logger.info("新增成功");
} else {
logger.info("新增失败");
}
}
public void delete(Serializable id) {
if(MemcachedUtil.getInstance().get("myUser")==null){
System.out.println("进入了数据查询");
int user=dao.delete(id);
//放入缓存中
MemcachedUtil.getInstance().set("myUser",10,user);
}else{
System.out.println("进入了缓存中查询");
MemcachedUtil.getInstance().get("myUser");
}
}
public void update(User t) {
int user=dao.update(t);
}
public List<User> findAll() {
if(MemcachedUtil.getInstance().get("myUser")==null){
System.out.println("进入了数据查询");
List<User> user=dao.findAll();
MemcachedUtil.getInstance().set("myUser",10,user);
return user;
}else{
System.out.println("进入了缓存中查询");
return (List<User>) MemcachedUtil.getInstance().get("myUser");
}
}
public User findById(Serializable id) {
if(MemcachedUtil.getInstance().get("myUser")==null){
System.out.println("进入了数据查询");
User user=dao.findById(id);
//放入缓存中
MemcachedUtil.getInstance().set("myUser",10,user);
return user;
}else{
System.out.println("进入了缓存中查询");
return(User) MemcachedUtil.getInstance().get("myUser");
}
}
public static void main(String[] args) {
UserImpServic use=new UserImpServic();
User s=new User();
try {
System.out.println(use.findById(53));
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try {
// new UtilClass().util_java();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
}
}
创建Newsimpl类
package Dao.servic.imp;
import java.io.Serializable;
import java.util.List;
import Dao.bean.News;
import Dao.serverce.NewsService;
import Dao.util.JdbcUtil;
public class NewsImpServic implements NewsService{
}
创建text包
创建ResultDemo类
package Dao.text;
import java.io.Serializable;
import java.util.List;
import java.util.Scanner;
import Dao.bean.User;
import Dao.dao.UserDao;
import Dao.impl.UserDaoImpl;
import Dao.serverce.UserService;
import Dao.servic.imp.UserImpServic;
import java.util.Scanner;
/**
* 相当于我们后续的jsp动态页面
*/
public class Resultshow {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
showMenu();
}
/**
* 一级菜单
*/
public static void showMenu() {
System.out.println("欢迎进入用户和新闻管理系统");
System.out.println("1:用户管理");
System.out.println("2:新闻管理");
System.out.println("请您选择:");
int choose = input.nextInt();
switch (choose) {
case 1: // 用户管理
showUser();
break;
}
}
/**
* 用户管理菜单
*/
private static void showUser() {
// 实例化UserService层的对象
UserService service = new UserImpServic();
User u=new User();
System.out
.println("========================================================");
System.out.println("欢迎进入用户管理系统");
System.out.println("1:登录");
System.out.println("2:删除");
System.out.println("3:修改");
System.out.println("4:查询所有");
System.out.println("5:查询指定用户信息");
System.out.println("6:返回上级目录");
System.out.println("请您选择:");
int choose = input.nextInt();
switch (choose) {
case 1: // 登录
userLogin(service);
break;
case 2: // 删除
userDelete(service);
break;
case 3: // 修改
updates(service);
break;
case 4: // 查询所有
Alllist(service);
break;
case 5: // 查询指定用户信息
userLogin(service);
break;
case 6: // 返回上级目录
showMenu();
break;
}
}
private static void Alllist(UserService service) {
List<User> user=service.findAll();
for (User user2 : user) {
int id=user2.getId();
String name=user2.getLoginName();
String Email=user2.getEmail();
String Password=user2.getPassword();
String bile=user2.getMobile();
String Code=user2.getIdentityCode();
System.out.println("您的个人信息如下:");
System.out.println(id);
System.out.println(name);
System.out.println(Email);
System.out.println(Password);
System.out.println(bile);
System.out.println(Code);
}
}
private static void updates(UserService service) {
User u=new User();
System.out.println("请输入id进行修改:");
int id = input.nextInt();
System.out.println("请您输入要修改的第一个内容:");
String Name = input.next();
System.out.println("请您输入要修改的第二个内容:");
String pas = input.next();
u.setLoginName(Name);
u.setPassword(pas);
u.setId(id);
service.update(u);
}
public static void userDelete(UserService service) {
System.out.println("请您输入需要删除的ID:");
int id = input.nextInt();
service.delete(id);
}
// 用户登录
public static void userLogin(UserService service) {
System.out.println("请您输入用户名:");
String loginName = input.next();
System.out.println("请您输入密码:");
String password = input.next();
User user = service.login(loginName, password);
System.out.println("您的个人信息如下:");
System.out.println(user.getId());
System.out.println(user.getLoginName());
System.out.println(user.getPassword());
System.out.println(user.getEmail());
System.out.println(user.getMobile());
System.out.println(user.getIdentityCode());
}
}
创建jdbcUtil包公共包
创建ConfigManager公共类
package Dao.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 读取properties文件的单例类
*/
//public class ConfigManager {
//
// // 01.创建本类的静态变量
// private static ConfigManager manager = new ConfigManager();
//
// private static Properties properties;
//
// // 02.私有化构造
//
// private ConfigManager() {
// // 实例化Properties对象
// properties = new Properties();
// InputStream stream = ConfigManager.class.getClassLoader()
// .getResourceAsStream("jdbc.properties");
// // 加载properties文件
// try {
// properties.load(stream);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try { // 关闭流
// stream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
//
// // 03.对外提供访问的接口
// public static synchronized ConfigManager getInstance() {
// return manager;
// }
//
// // 04.让用户传递一个文件中的key 我们返回文件中的value
// public static String getValue(String key) {
// return properties.getProperty(key);
// }
//
//}
public class ConfigManager {
// 01.创建本类的静态变量
private static ConfigManager manager = new ConfigManager();
private static Properties properties;
// 02.私有化构造
private ConfigManager() {
// 实例化Properties对象
properties = new Properties();
InputStream stream = ConfigManager.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
// 加载properties文件
try {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { // 关闭流
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 03.对外提供访问的接口
public static synchronized ConfigManager getInstance() {
return manager;
}
// 04.让用户传递一个文件中的key 我们返回文件中的value
public static String getValue(String key) {
return properties.getProperty(key);
}
}
创建jdbcUtil公共类
package Dao.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* 所有JDBC操作数据库的工具类
* 01.数据库四要素的获取
* 02.开启连接
* 03.关闭连接
* 04.公共的增删改
* 05.公共的查询
*/
public class JdbcUtil {
protected static Connection connection = null; // 便于我们释放资源
protected static PreparedStatement statement = null;
protected static ResultSet rs = null; // 查询数据返回的结果集
/**
* 获取连接
*/
public static boolean getConnection() throws ClassNotFoundException,
SQLException {
try {
// 通过反射机制获取数据库驱动包
Class.forName(ConfigManager.getInstance().getValue("jdbc.driver"));
// 通过DriverManager获取Conncetion连接对象
connection = DriverManager.getConnection(ConfigManager
.getInstance().getValue("jdbc.url"), ConfigManager
.getInstance().getValue("jdbc.userName"), ConfigManager
.getInstance().getValue("jdbc.password"));
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 释放资源
*/
public static void closeConnection() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 公共的增删改
*
* select * from student
* select * from student where id=?
* select * from student where id=? or name=?
*
* 我们可以确定的是有sql语句!因为只有sql语句才能操作数据库!
* 但是我么无法确定的是:
* 01.参数的个数
* 02.参数的类型
*
* 我们应该是考虑有参数 还是 没有参数? 有参数的!
* 考虑有1个参数还是有N个参数? 有N个参数的!
*
* 用户需要传递一个执行的sql语句
* 再传递一个参数列表!
* @throws SQLException
* @throws ClassNotFoundException
*/
public static int myExcuteUpdate(String sql, Object... param)
throws ClassNotFoundException, SQLException {
int rowNum = 0;
if (getConnection()) { // 证明有连接
statement = connection.prepareStatement(sql);
for (int i = 0; i < param.length; i++) { // 给sql语句中的? 一个一个赋值
statement.setObject(i + 1, param[i]);
}
rowNum = statement.executeUpdate();
}
closeConnection(); // 释放资源
return rowNum;
}
/**
* 公共的查询
*/
public static ResultSet myExcuteQuery(String sql, Object... param)
throws ClassNotFoundException, SQLException {
if (getConnection()) { // 证明有连接
statement = connection.prepareStatement(sql);
for (int i = 0; i < param.length; i++) { // 给sql语句中的? 一个一个赋值
statement.setObject(i + 1, param[i]);
}
rs = statement.executeQuery();
}
/**
* 在这里不能事先关闭资源,因为子类中有rs的具体使用 还需要用到连接!
* 子类使用完毕,自行了断!
*/
return rs;
}
}
创建MemcachedUtil公共类
package Dao.util;
import java.io.IOException;
import java.net.InetSocketAddress;
import net.spy.memcached.MemcachedClient;
public class MemcachedUtil {
//01.私有化本类对象
private static MemcachedUtil util;
private static MemcachedClient client=null;
static{
util=new MemcachedUtil();
try {
client=new MemcachedClient(new InetSocketAddress("127.0.0.1",11211));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//私有化构造
private MemcachedUtil(){
}
//对外提供访问的接口
public static MemcachedClient getInstance(){
return client;
}
}
创建ResultSetUtil公共类
package Dao.util;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*01.我们从数据库中获取的结果集就是ResultSet
*02.结果集中的类型我们确定吗???? 不确定 ===》 T
*03.sql语句一旦执行T的类型就确定了!
*04.通过反射机制 向实体类中的属性赋值
*/
public class ResultSetUtil {
/**
* 01.务必需要一个结果集 ResultSet ,才能获取T的类型
* 02.反射务必需要Class<T>
**/
public static <T> T findById(ResultSet rs, Class<T> c) {
T object = null;
try {
if (rs.next()) {
object = c.newInstance(); // 实例化对象
Field[] fields = c.getDeclaredFields(); // 获取实体类中所有的属性
for (Field field : fields) {
field.setAccessible(true); // 打开权限
field.set(object, rs.getObject(field.getName()));
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return object;
}
public static <T> List<T> findAll(ResultSet rs, Class<T> c) {
T object = null;
List<T> list = new ArrayList(); // 创建集合 保存每一个对象
try {
while (rs.next()) {
object = c.newInstance(); // 实例化对象
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true); // 打开权限
field.set(object, rs.getObject(field.getName()));
}
// 将对象加入到集合
list.add(object);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return list;
}
}
要导入包

创建jdbc.properties文件


浙公网安备 33010602011771号