当前位置:网站首页>How to access MySQL database through JDBC? Hand to hand login interface (illustration + complete code)

How to access MySQL database through JDBC? Hand to hand login interface (illustration + complete code)

2022-06-21 06:29:00 Xiaohuang Xiaohuang is no longer confused

Personal home page : Huang Xiaohuang's blog home page
Stand by me : give the thumbs-up Collection Focus on
Maxim : Only one step at a time can we accept the so-called luck

This article is from the column :JDBC From introduction to practice
Welcome to the support subscription column ️
 Insert picture description here


Write it at the front

The environment of this article :jdk1.8mysql8.0IntelliJ IDEA 2021.3 And DataGrip 2021.3;
  This article was written for the help of a fan , Coincidentally, it is the content of this experiment , So this article is only about JDBC How to access the database for operational description , Does not involve JDBC Basic related contents , If necessary, please look forward to the subsequent updates of the column . This article is only for students to exchange and study , Pictures are watermarked , Do not copy, If you want to reprint , Welcome private message .



1 Operation preparation

1.1 Import Mysql Corresponding jar package

  1. First of all to enter Mysql Download the official website : https://www.mysql.com/downloads/, Slide the page to the bottom , Click on MySQL Community (GPL) Downloads
     Insert picture description here
  2. choice Connector/J
     Insert picture description here
  3. choice General Availability(GA) Releases, stay Select Operating System Drop down list selection Platform Independent, Then select a file of any compressed package format Download, Follow the prompts to download , If you need another version , You can click on the Archives
     Insert picture description here
  4. Decompress after downloading , You can see the downloaded... In the current folder jar It's packed .
     Insert picture description here
  5. open idea Create a project JDBC And create Moudle JDBCtest, Create a directory under this module lib, And will just download the jar Copy the package .
     Insert picture description here
  6. Right click to jar package , Add as Library
     Insert picture description here

1.2 establish Mysql Database and basic tables

open datagrip, Create a new query , Create a with the following code myuser The database is used for JDBC Visit exercise , And create a table and enter data , The specific codes and table data are as follows :

CREATE DATABASE myuser;
USE myuser;
CREATE TABLE IF NOT EXISTS account(
    name VARCHAR(50) PRIMARY KEY NOT NULL ,
    password VARCHAR(50) NOT NULL
);

INSERT INTO account VALUES (' Zhang San ', '123');
INSERT INTO account VALUES (' Li Si ', '123');

 Insert picture description here


2 JDBC Basic experiments

2.1 To write JDBC Connect MySQL database myuser, Query and display account Table data instance

1. Create a project first 、 Package and Test.java, As shown in the figure below :
 Insert picture description here
2. Run the following JDBC Code , The running result diagram is attached to the code , Remember to set the database password ( Your password ) Change the location to your own password :

package JDBC_test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/** * @author  Xiaohuang Xiaohuang is no longer confused  * @version 1.0 */

public class Test {
    
    public static void main(String args[]) {
    
        try {
    
            Class.forName("com.mysql.cj.jdbc.Driver");     // load MYSQL JDBC The driver 
            System.out.println("Success loading Mysql Driver!");
        }
        catch (Exception e) {
    
            System.out.print("Error loading Mysql Driver!");
            e.printStackTrace();
        }
        try {
    
            Connection connect = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/myuser","root"," Your password ");
            // Establishing a connection ,URL by jdbc:mysql// Server address / database myuser , hinder 2 The first parameters are login user name and password 

            System.out.println("Success connect Mysql server!");
            Statement stmt = connect.createStatement(); // Create a running object 
            ResultSet rs = stmt.executeQuery("select * from account");// Execute the query account surface 

            while (rs.next()) {
    
                System.out.println(rs.getString("name"));// obtain name The value of the column ( String type )
            }
        }
        catch (Exception e) {
    
            System.out.print("get data error!");
            e.printStackTrace();
        }
    }
}

 Insert picture description here

2.2 To write JDBC Connect MySQL database , Realization myuser Increase of database 、 Delete 、 Examples of modified query

1. Create the following package 、 class :
 Insert picture description here
2. Through the following code myuser Database account The table implements the operations of adding, deleting, modifying and querying :
Tips: Also don't forget to “ Your password ” Change your database password !

package JDBC_test2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


/** * @author  Xiaohuang Xiaohuang is no longer confused  * @version 1.0 */


public class Test2 {
    
    static Connection conn;
    static Statement st;

    public static void main(String[] args) {
    
        insert();   // Insert add record 
        update();   // Update record data 
        delete();   // Delete record 
        query();    // Query records and display 
    }

    //(2) Access to connections , Before operation, you must obtain the connection with the database .
    private static Connection getConnection() {
    
        String driver = "com.mysql.cj.jdbc.Driver"; // If an error is reported, use com.mysql.jdbc.Driver
        String url = "jdbc:mysql://localhost:3306/myuser?serverTimezone=UTC "; //myuser Is the database name 
        String username = "root"; // Database user name 
        String password = " Your password "; // Database user password 
        Connection conn = null;
        try {
    
            Class.forName(driver); //classLoader, Load the corresponding driver 
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
    
            e.printStackTrace();
        } catch (SQLException e) {
    
            e.printStackTrace();
        }
        return conn;
    }

    //(3)  Insert (insert) operation 
    public static void insert() {
    
        conn = getConnection(); //  First get the connection , Connect to the database 
        try {
    
            String sql = "insert into account (name,password) values('lucy','123')"; //  Insert data sql sentence 
            st = (Statement) conn.createStatement();    //  Created to perform static sql Of the statement Statement object 
            int count = st.executeUpdate(sql);  //  To perform the insertion operation sql sentence , And return the number of inserted data 
            System.out.println(" towards account Insert in table  " + count + "  Data "); // Output the result of the insert operation 
            conn.close();   // Close database connection 
        } catch (SQLException e) {
    
            System.out.println(" Insert data failed " + e.getMessage());
        }
    }

    //(4)  to update (update) operation 
    public static void update() {
    
        conn = getConnection(); // Again, get the connection first , Connect to the database 
        try {
    
            String sql = "update account set password='0000' where name = ' Zhang San '";//  Update the data sql sentence 
            st = (Statement) conn.createStatement();    // Created to perform static sql Of the statement Statement object ,st It's a local variable 
            int count = st.executeUpdate(sql);//  To perform an update operation sql sentence , Returns the number of updated data 
            System.out.println("account Update in table  " + count + "  Data ");      // Output processing result of update operation 
            conn.close();   // Close database connection 
        } catch (SQLException e) {
    
            System.out.println(" Failed to update data ");
        }
    }

    //(5) Inquire about (query) operation 
    public static void query() {
    
        conn = getConnection(); // Again, get the connection first , Connect to the database 
        try {
    
            String sql = "select * from account";     //  Query data sql sentence 
            st = (Statement) conn.createStatement();    // Created to perform static sql Of the statement Statement object ,st It's a local variable 
            ResultSet rs = st.executeQuery(sql);    // perform sql Query statement , Returns the result set of the query data 
            System.out.println(" The final query result is :");
            while (rs.next()) {
     //  Judge if there is another data 
                //  Get the corresponding value according to the field name 
                String name = rs.getString("name");
                String password = rs.getString("password");
                // Output the value of each field of the found record 
                System.out.println(name + " " + password + " ");
            }
            conn.close();   // Close database connection 
        } catch (SQLException e) {
    
            System.out.println(" Failed to query data ");
        }
    }
    //(6) Delete (delete) operation 
        public static void delete () {
    
            conn = getConnection(); // Again, get the connection first , Connect to the database 
            try {
    
                String sql = "delete from account where name = ' Li Si '";//  Delete data's sql sentence 
                st = (Statement) conn.createStatement();    // Created to perform static sql Of the statement Statement object ,st It's a local variable 
                int count = st.executeUpdate(sql);//  perform sql Delete statements , Returns the number of deleted data 
                System.out.println("account In the table to delete  " + count + "  Data \n");    // Output the result of the delete operation 
                conn.close();   // Close database connection 
            } catch (SQLException e) {
    
                System.out.println(" Failed to delete data ");
            }

    }
}

 Insert picture description here
3. go back to datagrip see account The data table , The data of the discovery table was successfully updated :
 Insert picture description here


3 JDBC Advanced experiments —— Simple login interface

3.1 Concrete realization

1. MyConnection class , Realize database connection :
Tips: Also don't forget to “ Your password ” Change your database password !

package JDBC_test3;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


/** * @author  Xiaohuang Xiaohuang is no longer confused  * @version 1.0 */
public class MyConnection {
    
    public static Connection getConnection() {
    
        String driver = "com.mysql.cj.jdbc.Driver";// Use Jar Package driven 
        String url = "jdbc:mysql://localhost:3306/myuser?serverTimezone=UTC";// Link database port , Database name 
        String username = "root";// Database user name 
        String password = " Your password ";// Database password 
        Connection conn = null;
        try {
    
            Class.forName(driver); //classLoader, Load the corresponding driver 
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
    // Exception trapping 
            e.printStackTrace();
        } catch (SQLException e) {
    
            e.printStackTrace();
        }
        return conn;
    }

}

2. Login class , Realize the login interface :

package JDBC_test3;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/** 1. @author  Xiaohuang Xiaohuang is no longer confused  2. @version 1.0 */
public class Login  extends JFrame{
    

    private JLabel JLname;
    private JLabel JLpwd;
    private JTextField JTname;
    private JPasswordField JTpwd;
    private JButton JBsure;
    private JButton JBexit;

    public Login(String title){
    
        super(title);
        JLname = new JLabel(" user name :");// Set up Label And button name 
        JLpwd = new JLabel(" The secret   code :");
        JTname = new JTextField(20);
        JTpwd = new JPasswordField(20);
        JBsure = new JButton(" determine ");
        JBexit = new JButton(" Cancel ");

        JLname.setBounds(40, 40, 60, 25);// Set up Label And button size 
        JTname.setBounds(100, 40, 170, 25);
        JLpwd.setBounds(40,80,60,25);
        JTpwd.setBounds(100,80,170,25);
        JBsure.setBounds(110,130,60,25);
        JBexit.setBounds(180,130,60,25);


        this.setLayout(null);
        this.add(JLname);
        this.add(JTname);
        this.add(JLpwd);
        this.add(JTpwd);
        this.add(JBsure);
        this.add(JBexit);

        JBsure.addActionListener(new ActionListener(){
    // Add button listening 

            public void actionPerformed(ActionEvent arg0) {
    
                dispose();
                loginCheak(JTname,JTpwd);
            }
        });

        JBexit.addActionListener(new ActionListener(){
    

            public void actionPerformed(ActionEvent e) {
    

                System.exit(0);
            }

        });

    }

    public void loginCheak(JTextField tf,JPasswordField pf) {
    
        String username = tf.getText();
        String password = String.valueOf(pf.getPassword());
        System.out.println(password);// Output the filled password 

        if("".equals(username)){
    // Judge whether the user name is empty 
            JOptionPane.showMessageDialog(null," Account number cannot be empty ","Warning",JOptionPane.WARNING_MESSAGE);
            return;
        }
        if("".equals(password)){
    // Determine whether the password is empty 
            JOptionPane.showMessageDialog(null," The password cannot be empty ","Warning",JOptionPane.WARNING_MESSAGE);
            return;
        }
        try{
    
            new MyConnection();
            Connection con = MyConnection.getConnection() ;// call MyConnection.java Medium getConnection Method 
            Statement stmt=con.createStatement();
            String sql = "select * from account where name = '" + username + "' and password = '" + password + "'"; //SQL Select the query statement 
            ResultSet rs=stmt.executeQuery(sql);

            if (rs.next()) {
    
                JOptionPane.showMessageDialog(this, " Successfully logged in ", " Tips ",  JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
            else {
    
                JOptionPane.showMessageDialog(this, " Wrong account number or password !", " Warning ",  JOptionPane.WARNING_MESSAGE);
                pf.requestFocus();
            }
        }catch(Exception e){
    
            e.printStackTrace();
        }
    }
    public static void main (String []args){
    // The main function 
        Login ft=new Login(" Welcome landing ");
        ft.setSize(340, 240);
        ft.setLocation(300, 300);
        ft.setVisible(true);
        ft.setResizable(false);
    }
}

3.2 Effect display

  1. The login interface shows , Enter the user name and password in sequence Zhang San 、0000:
     Insert picture description here

  2. Click ok , Prompt for successful login :
     Insert picture description here

  3. Rerun , Enter Zhang San and an incorrect password , Prompt login failed :
     Insert picture description here

  4. Click directly to log in , Prompt user name cannot be empty :
     Insert picture description here


At the end

The above is the whole content of this article , The follow-up will continue Free update , If the article helps you , Please use your hands Point a praise + Focus on , Thank you very much ️ ️ ️ !
If there are questions , Welcome to the private letter or comment area !
 Insert picture description here

Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
 Insert picture description here

原网站

版权声明
本文为[Xiaohuang Xiaohuang is no longer confused]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210615019887.html