目录
一.数据库连接步骤(作为一个方法抽取出来)
1.创建一个工具类,专门用来存放频繁使用的代码,避免代码冗余。
2.连接
3.如何使用
4.导入Jar包
5.附上一个测试数据库连接的代码
二.一个简单的登录小项目
1.分层情况
1.分三层,三个包,分别是:dao、service、ui
2.dao
3.service
4.ui
2.代码实现
今日要点:
1.数据库连接步骤
2.学习如何给项目分层分包,每一层做什么功能
一.数据库连接步骤(作为一个方法抽取出来)
1.创建一个工具类,专门用来存放频繁使用的代码,避免代码冗余。
2.连接
连接代码:
public class JdbcUtils {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//1.连接数据库
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf8",
"root", "123456");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
3.如何使用
把下面语句放入方法中即可
Connection conn = null;
conn = JdbcUtils.getConnection();
4.导入Jar包
1)点击项目文件夹右键
2)新建文件夹,命名为lib。注意,此文件夹是和src文件夹是在同一等级的
3)把jar包复制进lib中
4)点击jar包,右键
5)运行
5.附上一个测试数据库连接的代码
package com.gongsi.cn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestJdbc {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm", "root", "123456");
Statement state = conn.createStatement();
//SELECT deptno,dname,loc FROM dept
String sqlAll = "SELECT deptno,dname,loc FROM dept";
ResultSet rs = state.executeQuery(sqlAll);
while (rs.next()) {
int deptno = rs.getInt("deptno");
String dname = rs.getString("dname");
String loc = rs.getString("loc");
System.out.println(deptno+"\t"+dname+"\t"+loc);
}
rs.close();
state.close();
conn.close();
}
}
注意:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm", "root", "123456");
这两句根据自己电脑的改。
一定要确保数据库已经开启,并且sql语句是正确的,以及数据库里面有数值。
二.一个简单的登录小项目
1.分层情况
1.分三层,三个包,分别是:dao、service、ui
1)dao:和数据库连接
2)service:业务处理,异常处理
3)ui:界面设计
2.dao
创建三个东西:entity包,impl包,接口
1)entity包:里面装的是数据库里的某一个表格。也就是我们要操作的数据
2)impl包:里面装的是这个表格的接口的实现类
3)接口 这个表格的接口。只定义方法,为了使方法名规范。
4)utils是工具类
3.service
有一个impl包和接口
1)impl 用来装接口的实现类
2)接口 定义接口。接口是一种约束
4.ui
不需要建包
2.代码实现
dao包下的:
package com.gongsi.cn.dao.entity;
import java.util.Date;
/*
* `EMPNO` int(11) NOT NULL DEFAULT '0',
`ENAME` varchar(10) DEFAULT NULL,
`PASSWORD` varchar(50) DEFAULT NULL,
`JOB` varchar(9) DEFAULT NULL,
`MGR` int(11) DEFAULT NULL,
`HIREDATE` date DEFAULT NULL,
`SAL` double DEFAULT NULL,
`COMM` double DEFAULT NULL,
`DEPTNO` int(11) DEFAULT NULL,
PRIMARY KEY (`EMPNO`),
KEY `FK_DEPTNO` (`DEPTNO`),
*
*/
public class Emp {
private int empno;
private String ename;
private String password;
private String job;
private int mgr;
private Date hireDate;
private double sal;
private double comm;
private int deptno;
@Override
public String toString() {
return "Emp [empno=" + empno + ", ename=" + ename + ", password=" + password + ", job=" + job + ", mgr=" + mgr
+ ", hireDate=" + hireDate + ", sal=" + sal + ", comm=" + comm + ", deptno=" + deptno + "]";
}
public Emp() {
super();
}
public Emp(int empno, String ename, String password, String job, int mgr, Date hireDate, double sal, double comm,
int deptno) {
super();
this.empno = empno;
this.ename = ename;
this.password = password;
this.job = job;
this.mgr = mgr;
this.hireDate = hireDate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public double getComm() {
return comm;
}
public void setComm(double comm) {
this.comm = comm;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
}
package com.gongsi.cn.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.gongsi.cn.dao.IEmpDao;
import com.gongsi.cn.dao.entity.Emp;
import com.gongsi.cn.dao.utils.JdbcUtils;
public class EmpDaoImpl implements IEmpDao{
/**
* 登录的查询 跟数据库打交道的方法
* @param emp 使用实体类对象进行传入参数
* @return 查询到的数据
*/
public Emp getEmpByNameAndPassword(Emp emp) {
Emp resultEmp = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 2.得到数据库连接(桥)
conn = JdbcUtils.getConnection();
// 3.得到statement接口指向的对象,发送sql语句到数据库中执行,并返回结果集
// SELECT * FROM emp WHERE ename = '张三' AND `password` = '111'
String sqlLogin = "SELECT empno,ename,`password`,job,mgr,hiredate,sal,comm,deptno FROM emp WHERE ename = ? AND `password` = ?";
ps = conn.prepareStatement(sqlLogin);
ps.setObject(1, emp.getEname());
ps.setObject(2, emp.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
resultEmp = new Emp();
resultEmp.setEmpno(rs.getInt("empno"));
resultEmp.setEname(rs.getString("ename"));
resultEmp.setPassword(rs.getString("password"));
resultEmp.setJob(rs.getString("job"));
resultEmp.setMgr(rs.getInt("mgr"));
resultEmp.setHireDate(rs.getDate("hiredate"));
resultEmp.setSal(rs.getDouble("sal"));
resultEmp.setComm(rs.getDouble("comm"));
resultEmp.setDeptno(rs.getInt("deptno"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtils.closeAll(rs, ps, conn);
}
return resultEmp;
}
}
package com.gongsi.cn.dao.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtils {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//1.连接数据库
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf8",
"root", "123456");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//2.增删改
public static int executeUpdate(String sql,Object...objects ) {
int rows = -1;
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
if (objects!=null) {
for (int i = 0; i < objects.length; i++) {
ps.setObject((i+1), objects[i]);
}
}
rows = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JdbcUtils.closeAll(null, ps, conn);
}
return rows;
}
//3.关闭资源
public static void closeAll(ResultSet rs,Statement state,Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (state != null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
*
*/
package com.gongsi.cn.service;
import com.gongsi.cn.dao.entity.Emp;
/**
* @author Administrator
*
*/
public interface IEmpService {
public Emp loginService(Emp emp) throws Exception;
}
Service包下的:
package com.gongsi.cn.service.impl;
import com.gongsi.cn.dao.IEmpDao;
import com.gongsi.cn.dao.entity.Emp;
import com.gongsi.cn.dao.impl.EmpDaoImpl;
import com.gongsi.cn.service.IEmpService;
public class EmpServiceImpl implements IEmpService{
/**
* @Autor:Dailyrs
@Description 异常检查
@param EmpDaoImpl接收的数据
@return 返回从EmpDaoImpl接收到的数据
*/
public Emp loginService(Emp emp)throws Exception {
Emp resultEmp = null;
IEmpDao get=new EmpDaoImpl();
resultEmp = get.getEmpByNameAndPassword(emp);
if (resultEmp==null) {
throw new Exception("用户名或者密码错误!!");
}
return resultEmp;
}
}
/**
*
*/
package com.gongsi.cn.service;
import com.gongsi.cn.dao.entity.Emp;
/**
* @author Administrator
*
*/
public interface IEmpService {
public Emp loginService(Emp emp) throws Exception;
}
ui包下的:
package com.gongsi.cn.ui;
import java.util.Scanner;
import com.gongsi.cn.dao.entity.Emp;
import com.gongsi.cn.service.IEmpService;
import com.gongsi.cn.service.impl.EmpServiceImpl;
public class LoginView {
/**
*
* @Autor:Dailyrs
@Description 登录界面输入数据
@param
@return 登录成功/登录失败
*/
public void loginView() {
IEmpService em=new EmpServiceImpl();
Scanner input = new Scanner(System.in);
System.out.print("请输入用户名:");
String name = input.next();
System.out.print("请输入密码:");
String password = input.next();
Emp emp = new Emp();
emp.setEname(name);
emp.setPassword(password);
try {
Emp restulEmp = em.loginService(emp);
if (restulEmp!=null) {
System.out.println("登录成功了!!");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("登录失败了");
}
}
}
/**
*
*/
package com.gongsi.cn.ui;
/**
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
LoginView loginTest=new LoginView();
loginTest.loginView();
}
}
不加界面的话,这个代码已经完成
下面是自己画的两个简陋界面。画完之后只需要改两个地方的代码
package com.gongsi.cn.ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.gongsi.cn.dao.entity.Emp;
import com.gongsi.cn.service.impl.EmpServiceImpl;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
public class LoginFram extends JFrame {
private JPanel contentPane;
private JTextField userNameTf;
private JTextField passwordPf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginFram frame = new LoginFram();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LoginFram() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(617, 439);
this.setLocationRelativeTo(null);
//setBounds(100, 100, 617, 439);
contentPane = new JPanel();
contentPane.setBackground(Color.CYAN);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel userNameLbl = new JLabel("用户名");
userNameLbl.setHorizontalAlignment(SwingConstants.CENTER);
userNameLbl.setBounds(155, 139, 72, 18);
contentPane.add(userNameLbl);
userNameTf = new JTextField();
userNameTf.setBounds(229, 136, 181, 24);
contentPane.add(userNameTf);
userNameTf.setColumns(10);
JLabel passwordLbl = new JLabel("密 码");
passwordLbl.setHorizontalAlignment(SwingConstants.CENTER);
passwordLbl.setBounds(155, 184, 72, 18);
contentPane.add(passwordLbl);
passwordPf = new JTextField();
passwordPf.setBounds(228, 181, 182, 24);
contentPane.add(passwordPf);
passwordPf.setColumns(10);
JButton loginBtn = new JButton("登录");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
login();
}
});
loginBtn.setBounds(229, 241, 72, 24);
contentPane.add(loginBtn);
JButton resetBtn = new JButton("重置");
resetBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
resetBtn.setBounds(338, 241, 72, 24);
contentPane.add(resetBtn);
}
protected void login() {
EmpServiceImpl empServiceImpl=new EmpServiceImpl();
String userName=userNameTf.getText();
String password=passwordPf.getText();
Emp emp = new Emp();
emp.setEname(userName);
emp.setPassword(password);
try {
Emp restulEmp = empServiceImpl.loginService(emp);
if (restulEmp!=null) {
mainFram main=new mainFram();
main.setVisible(true);
this.dispose();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("登录失败了");
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
package com.gongsi.cn.ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSplitPane;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class mainFram extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFram frame = new mainFram();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainFram() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1200, 700);
this.setLocationRelativeTo(null);
//setBounds(100, 100, 1200, 700);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel buttomPanel = new JPanel();
buttomPanel.setBackground(Color.PINK);
contentPane.add(buttomPanel, BorderLayout.SOUTH);
buttomPanel.setLayout(null);
JPanel copyRightPanel = new JPanel();
copyRightPanel.setBounds(-5, 5, 10, 10);
buttomPanel.add(copyRightPanel);
JLabel lblNewLabel = new JLabel("版权在这里");
lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 50));
copyRightPanel.add(lblNewLabel);
JPanel timePanel = new JPanel();
timePanel.setBounds(-5, 20, 10, 10);
buttomPanel.add(timePanel);
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.PINK);
contentPane.add(topPanel, BorderLayout.NORTH);
JLabel titleLbl = new JLabel("排队叫号后台管理系统");
titleLbl.setBackground(Color.PINK);
titleLbl.setFont(new Font("老報宋", Font.PLAIN, 50));
topPanel.add(titleLbl);
JSplitPane centerPanel = new JSplitPane();
contentPane.add(centerPanel, BorderLayout.CENTER);
}
}
LoginFram中:
登录成功:
登录失败: