这几天逼着交Java,借鉴各位师傅的做出来这么个简陋的东西,各位大师傅不要笑我。(学都没有学过Java的我,QAQ~)
下面针对的都是SQL Server系列的连接,如果你使用MySQL那么不必看关于连接数据库的介绍。
数据库驱动JDBC在Ecilpse安装教程:点击进入
项目及素材下载链接:点击下载
常见问题:
端口拦截
连接数据库时,端口被防火墙拦截,检查端口是否开放,然后重启sql server服务。
代码使用
在使用代码时,需要额外创建一个包,如图创建
数据库账号密码问题
Java连接数据库需要SQL登录方式,需要账号密码,如果说不知道自己是否是混合登录,或者说忘记密码,可以这样做:
打开数据库软件,连接数据库(Windows登录就可以了)。
右键你的本地数据库
打开属性,点击安全性,查看是否是SQL Server和Windows混合登录。(不是就点上)
接着依次打开安全性-->登录名,那个sa就是我的管理员账号。
双击点开,就可以在账号框和密码框进行账号名,密码更改,最后确认就行。
如果没有账号的话,右键登录名,选择新建登录名,重新创建一个SQL登陆方式的账户。
查看自己的数据库名称:
这个“master”就是我的数据库名称,同时也储存着我的数据。
代码:
Login.java
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField; import pack.VerCode;
public class Login {
String StudentAccount="123456";
String StudentPassWord="123456";
JLabel L, L1, L2, L3, L4, BK;
JTextField te1, te3;
JPasswordField te2;
JRadioButton value1, value2;
JButton B1, B2;
ButtonGroup bg;
JPanel jp1,jp2,jp3,jp4;
//设置图标
Icon v1 = new ImageIcon("p3.png");
Icon v2 = new ImageIcon("p4.png");
Icon v3 = new ImageIcon("p5.png");
Icon v4 = new ImageIcon("p6.png");
private VerCode VerCode = new VerCode();//引用验证码函数 public static void main(String[] args) {
Login frame=new Login();
frame.show();
}
JFrame frame=new JFrame();//frame界面
public void show() {
setBackgroudImage(); Toolkit tk = Toolkit.getDefaultToolkit();//默认加载方式
Image image = new ImageIcon(getClass().getResource("p6.png")).getImage();//设置光标图片
Cursor cursor = tk.createCustomCursor(image, new Point(10, 10), "biubiubiu");//光标image属性,指定光标中心,光标文字描述
frame.setCursor(cursor); L1=new JLabel("<html>账号:</html>");
L1.setIcon(v1);
te1=new JTextField(80);
//设置密码窗口,使用'*'隐藏密码
L2=new JLabel("<html>密码:</html>");
L2.setIcon(v2);
te2=new JPasswordField(80);//
te2.setEchoChar('*');
L4 = new JLabel("验证码:");
L4.setIcon(v3);
te3=new JTextField(80); //设置登录身份选择按钮
jp2 = new JPanel();
L3 = new JLabel("身份:");
L3.setIcon(v4);
value2=new JRadioButton("学生");
SetBt(value2); //设置位置和大小
L1.setBounds(60, 90, 60, 40);
L2.setBounds(60, 140, 60, 40);
L3.setBounds(60, 240, 60, 40);
L4.setBounds(60, 190, 60, 40); jp2.setBounds(80, 240, 60, 40);
te1.setBounds(130, 90, 150, 30);
te2.setBounds(130, 140, 150, 30);
te3.setBounds(130, 190, 150, 30);
VerCode.setBounds(290, 190, 100, 40);
value2.setBounds(120, 240, 60, 40); //设置'登录'及'重置'按钮
B1=new JButton("登录");
B1.setBounds(120, 280, 80, 40);
SetBt(B1);
ButtonListener li1=new ButtonListener(te1,te2); B2=new JButton("注册");
B2.setBounds(250, 280, 80, 40);
SetBt(B2);
ButtonListener li2=new ButtonListener(te1,te2); //设置监听
B1.addActionListener(li1);
B2.addActionListener(li2); //组键添加到窗口
frame.setLayout(null);
//frame.add(L); frame.add(L1);
frame.add(te1); frame.add(L2);
frame.add(te2); frame.add(L3);
frame.add(value2); frame.add(L4);
frame.add(te3);
frame.add(VerCode); frame.add(B1);
frame.add(B2);
frame.setVisible(true);//窗体设置为可见 frame.setTitle("学生管理系统");
frame.setSize(700,403);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false); } private void SetBt(JButton b12) {
b12.setBackground(new Color(102, 0, 204));//设置色值
b12.setFont(new Font("宋体", Font.BOLD, 24));//设置字体,样式。字号
b12.setOpaque(false);//设置控件透明
b12.setBorder(BorderFactory.createEmptyBorder()); }
private void SetBt(JRadioButton b12) {
b12.setBackground(new Color(102, 0, 204));
b12.setFont(new Font("Dialog", Font.BOLD, 15));
b12.setOpaque(false);//设置控件透明
b12.setBorder(BorderFactory.createEmptyBorder()); } public boolean isValidCodeRight() {//判断验证码是否有效
if(te3 == null) {
return false;
}else if(VerCode == null) {
return true;
}else if(VerCode.getCode() .equals(te3.getText())) {
return true;
}else
return false;
} private void setBackgroudImage() {
// TODO Auto-generated method stub
((JPanel) frame.getContentPane()).setOpaque(false);
ImageIcon img = new ImageIcon("3.gif"); // 添加图片
BK = new JLabel(img);
frame.getLayeredPane().add(BK, new Integer(Integer.MIN_VALUE));
BK.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
} //创建类实现接口
public class ButtonListener implements java.awt.event.ActionListener{ //实现ActionListener 接口 implement
JTextField te1=new JTextField(); //传参
JPasswordField te2=new JPasswordField();
Function hua=new Function(); //一个画板对象
ButtonListener(JTextField te1,JPasswordField te2) {//重载 窗体上的账号框,密码框传到监听上来
this.te1=te1;
this.te2=te2;
}
public ButtonListener(JTextField ID) {
// TODO Auto-generated constructor stub
}
@Override
public void actionPerformed(ActionEvent ch) {
// TODO Auto-generated method stub
if(ch.getActionCommand()=="登录")
{
if(te3.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "请输入验证码!");
}else {
if(!isValidCodeRight()) {
JOptionPane.showMessageDialog(null, "验证码错误,请重新输入!","错误",JOptionPane.ERROR_MESSAGE);
hua.bClear(te3);
}
else if(value2.isSelected())
{
hua.Student(StudentAccount, StudentPassWord, te1, te2, frame, hua);//学生
} else if(ch.getActionCommand()=="重置")
{
hua.Clear(te1, te2);
}
} } } }
}
VerCode.java
package pack;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener; import java.util.Random; import javax.swing.JComponent; public class VerCode extends JComponent implements MouseListener { private String typeface; private int V1, V2 = 30; private int Len = 4; private Random random = new Random(); public VerCode() {
V1 = this.Len * 16 + (this.Len - 1) * 10;
setPreferredSize(new Dimension(V1, V2));
setSize(V1, V2);
this.addMouseListener(this);
setToolTipText("点击可以更换验证码");
} public int getCodeLength() {
return Len;
} //设置验证码长度
public void setCodeLength(int Len) {
if(Len < 4) {
this.Len = 4;
} else {
this.Len = Len;
} } public String getCode() {
return typeface;
} //产生随机颜色
public Color getRandColor(int min, int max) { if (min > 255)
min = 255;
if (max > 255)
max = 255;
int red = random.nextInt(max - min) + min;
int green = random.nextInt(max - min) + min;
int blue = random.nextInt(max - min) + min;
return new Color(red, green, blue);
}
//设置验证码字母
protected String generateCode() {
char[] codes = new char[this.Len];
for (int i = 0, len = codes.length; i < len; i++) {
if (random.nextBoolean()) {
codes[i] = (char) (random.nextInt(26) + 65);
} else {
codes[i] = (char) (random.nextInt(26) + 97);
}
}
this.typeface = new String(codes);
return this.typeface;
} @Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(this.typeface == null || this.typeface.length() != this.Len) {
this.typeface = generateCode();
}
V1 = this.Len * 16 + (this.Len - 1) * 10;
super.setSize(V1, V2);
super.setPreferredSize(new Dimension(V1, V2));
Font mFont = new Font("Arial", Font.BOLD | Font.ITALIC, 25);
g.setFont(mFont);
//绘制验证码的背景的矩形轮廓
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(getRandColor(200, 250));
g2d.fillRect(0, 0, V1, V2);
g2d.setColor(getRandColor(180, 200));
g2d.drawRect(0, 0, V1 - 1, V2 - 1);
//绘制验证码背景的线
int i = 0, len = 150;
for (; i < len; i++) {
int x = random.nextInt(V1 - 1);
int y = random.nextInt(V2 - 1);
int x1 = random.nextInt(V1 - 10) + 10;
int y1 = random.nextInt(V2 - 4) + 4;
g2d.setColor(getRandColor(180, 200));
g2d.drawLine(x, y, x1, y1);
} //绘制出验证码的具体字母
i = 0; len = this.Len;
FontMetrics fm = g2d.getFontMetrics();
int base = (V2 - fm.getHeight())/2 + fm.getAscent();
for(;i<len;i++) {
int b = random.nextBoolean() ? 1 : -1;
g2d.rotate(random.nextInt(10)*0.01*b);
g2d.setColor(getRandColor(20, 130));
g2d.drawString(typeface.charAt(i)+"", 16 * i + 10, base);
}
} //下一个验证码
public void nextCode() {
generateCode();
repaint();
} @Override
public void mouseClicked(MouseEvent e) { nextCode();
} @Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub } @Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub } @Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub } @Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub }
}
Function.java
import java.awt.*; import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
import java.sql.*; import javax.swing.*; public class Function extends JFrame implements ActionListener{
String StuID, Stud_Name;
String num;
JTextField ID;
JButton Select;
JPanel Va, Vb;
JTable ival;
JScrollPane qval;
DefaultTableModel rval;
JLabel label;
static Connection ct;
PreparedStatement ps;
ResultSet rs; //Connect connect = new Connect();
//学生登录界面
public void StudentShow() {
Icon v1 = new ImageIcon("p3.png");
Va=new JPanel();
label=new JLabel();
label.setIcon(v1);
label.setText("学号");
ID = new JTextField(15); Select=new JButton("查询");
Select.addActionListener(this);
//界面表格名添加
String[] colnames = { "学号","姓名", "学院", "Java", "Python", "数据结构"};
rval = new DefaultTableModel(colnames, 3);
ival = new JTable(rval);
qval = new JScrollPane(ival); Va = new JPanel();
Vb = new JPanel(); Va.add(label);
Va.add(ID);
Va.add(Select);
Vb.add(qval);
//查询位置调整
this.add(Va,BorderLayout.SOUTH);
this.add(Vb); //界面属性设置
this.setLocationRelativeTo(null); //居中
this.setVisible(true);
this.setSize(500,600);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setTitle("学生管理系统"); } //学生登录判断
public void Student(String StudentAccount, String StudentPassWord,JTextField te1, JPasswordField te2, JFrame frame, Function hua)
{
if(StudentAccount.equals(te1.getText())&&StudentPassWord.equals(te2.getText()))
{
JOptionPane.showMessageDialog(this, "登录成功!");
frame.setVisible(false);//窗口不可见
hua.StudentShow();//调用一个画板对象中的函数 弹出一个界面
}else if(te1.getText().isEmpty()&&te2.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "请输入账号或密码");
}else if(te1.getText().isEmpty())
{
JOptionPane.showMessageDialog(this,"请输入用户名!");
}else if(te2.getText().isEmpty())
{
JOptionPane.showMessageDialog(this,"请输入密码!");
}else
{
JOptionPane.showMessageDialog(this,"<html>账户或密码错误!!!<br>请重新输入</html>","错误",JOptionPane.ERROR_MESSAGE);
//清空输入框
Clear(te1, te2);
}
}
//清空文本框和密码框
public void Clear(JTextField te1, JPasswordField te2) {
te1.setText("");
te2.setText("");
}
//清空密码
public void aClear(JPasswordField te2)
{
te2.setText("");
}
public void bClear(JTextField te3)
{
te3.setText("");
} public class ButtonListener implements java.awt.event.ActionListener{ //实现ActionListener 接口 implement
JTextField te1=new JTextField(); //传参
JPasswordField te2=new JPasswordField();
Function hua=new Function(); //一个画板对象
ButtonListener(JTextField te1,JPasswordField te2) {//重载 窗体上的账号框,密码框传到监听上来
this.te1=te1;
this.te2=te2;
}
public ButtonListener(JTextField ID) {
// TODO Auto-generated constructor stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub }
} public void actionPerformed(ActionEvent ch) {
if(ch.getActionCommand()=="查询")
{
Connect.ConnectSQL();//连接数据库
Connect.GetStudeInfor(ID.getText());//获取ID ID.setText("");
ival.setValueAt(Connect.sID, 0, 0);
ival.setValueAt(Connect.sname, 0, 1);
ival.setValueAt(Connect.Dept, 0 , 2);
ival.setValueAt(Connect.Java, 0, 3);
ival.setValueAt(Connect.Python, 0, 4);
ival.setValueAt(Connect.DataStructure, 0, 5);
} }
}
Connect.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import javax.swing.JOptionPane;
import java.awt.Cursor;
public class Connect {
static String sID, sname, Dept, Java, Python, DataStructure;
static Connection Co;
static PreparedStatement nValue;
static ResultSet ResultInfor;
static Statement ST;
//数据库连接函数
public static void ConnectSQL() {
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=master;";//master是自己储存数据的数据库名
try {
// 连接数据库
Co = DriverManager.getConnection(url, "sa", "biubiubiu");//sa是SQL账号,后面是密码
// 建立Statement对象
ST = Co.createStatement();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,"<html>数据库连接错误!!!<br>请联系管理员修复。</html>","错误",JOptionPane.ERROR_MESSAGE);
}
} public static void GetStudeInfor(String Str) {
try {
// 给?赋值,防止SQL注入,
String sql = "select * from Infor where Stud_ID = ?";
nValue = Co.prepareStatement(sql);
nValue.setString(1, Str);
ResultInfor = nValue.executeQuery();
if(ResultInfor.next())
{
//获取学生信息
sID = ResultInfor.getString("Stud_ID");
sname = ResultInfor.getString("Stud_Name");
Dept = ResultInfor.getString("Stud_Dept");
Java = ResultInfor.getString("JavaGrade");
Python = ResultInfor.getString("PythonGrade");
DataStructure = ResultInfor.getString("DataStructureGrade");
JOptionPane.showMessageDialog(null, "查询成功!");
}else
{
JOptionPane.showMessageDialog(null, "没有此学生!");
} } catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}