当前位置:网站首页>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 luckThis article is from the column :JDBC From introduction to practice
Welcome to the support subscription column ️
Write it at the front
The environment of this article :jdk1.8、mysql8.0、IntelliJ 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 .
List of articles
1 Operation preparation
1.1 Import Mysql Corresponding jar package
- 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

- choice Connector/J

- 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

- Decompress after downloading , You can see the downloaded... In the current folder jar It's packed .

- 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 .

- Right click to jar package , Add as Library

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');

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 :
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();
}
}
}

2.2 To write JDBC Connect MySQL database , Realization myuser Increase of database 、 Delete 、 Examples of modified query
1. Create the following package 、 class :
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 ");
}
}
}

3. go back to datagrip see account The data table , The data of the discovery table was successfully updated :
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
The login interface shows , Enter the user name and password in sequence Zhang San 、0000:

Click ok , Prompt for successful login :

Rerun , Enter Zhang San and an incorrect password , Prompt login failed :

Click directly to log in , Prompt user name cannot be empty :

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 !
Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
边栏推荐
- Construction and protection of small-scale network examination
- 【毕业季】纸短情长,浅谈大二以前的学习经历
- What is the shortcut button 4 click of pychart?
- leetcode数据库mysql题目(难度:简单)
- Niuke-top101-bm25
- Roll in Dachang series LRU cache elimination algorithm
- Cache cache (notes on principles of computer composition)
- Why should I use the source code of nametuple replace(‘,‘, ‘ ‘). Split() instead of split(‘,‘)
- 【JDBC从入门到实战】JDBC基础通关教程(全面总结上篇)
- 三维引擎软件Vizard入门
猜你喜欢

FPGA - 7系列 FPGA SelectIO -06- 逻辑资源之ODELAY

用递归和循环两种方法解决华为4月20日机试第一题(100分)

FPGA - 7 Series FPGA selectio -01- introduction and DCI technology introduction
![[MySQL] SQL statement execution process of MySQL](/img/c8/76726de7ae3521f709e336a60ae3a2.png)
[MySQL] SQL statement execution process of MySQL

Why should I use the source code of nametuple replace(‘,‘, ‘ ‘). Split() instead of split(‘,‘)

Backtracking method of graph coloring problem (the most easy to understand)

Dragon Boat Festival - simple side navigation bar
![Leetcode 75 - 颜色分类 [Medium] 三种实现方法](/img/52/61ae051babf6b5c6b603093a17e55c.png)
Leetcode 75 - 颜色分类 [Medium] 三种实现方法

第6期:大学生应该选择哪种主流编程语言
![Leetcode 75 - three implementation methods of color classification [medium]](/img/52/61ae051babf6b5c6b603093a17e55c.png)
Leetcode 75 - three implementation methods of color classification [medium]
随机推荐
Memorizing Normality to Detect Anomaly: Memory-augmented Deep Autoencoder for Unsupervised Anomaly D
粽子大战 —— 猜猜谁能赢
当今的数学是否过于繁琐?
第7期:内卷和躺平,你怎么选
nametuple的源码为什么要使用.replace(‘,‘, ‘ ‘).split()而不是.split(‘,‘)
第4篇:从硬件/源码视角看JVM内存模型
827. 最大人工岛 并查集
数据库有用户更改密码问题
docker 安装mysql
【你所熟悉的网络真的安全吗?】万字文
Does intelligence need a body
判断一棵树是否为完全二叉树
tf. compat. v1.MetaGraphDef
FPGA - 7 Series FPGA selectio -05- logic of logic resources
FPGA - 7系列 FPGA SelectIO -06- 逻辑资源之ODELAY
Required questions for group planning: storage system (completed, with detailed analysis attached)
Aurora8B10B IP使用 -01- 简介与端口描述
递归建立链式二叉树,完成前中后序遍历以及其他功能(附源码)
MySQL数据库基础:连接查询
Recursively establish a chained binary tree, complete the traversal of the first, middle and last order and other functions (with source code)