
這幾天逼着交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(); } } }
