Java training GUI student management system--create database student management system

Create a database student management system

Create a database connection management class

Define database connection attribute constants in the program

1. Create dbutil in the src package.
dbutil
2. Create the ConnectionManager class in the dbutil package.
ConnectionManager
Here are some 详细代码.

package net.lyq.student.dbutil;

import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager {
    private static final String DRIVER = "com.mysql.jbdc.Driver";           //数据库驱动程序
    private static final String URL = "jdbc:mysql://localhost:3306/student";//数据库统一资源标识符
    private static final String USER = "root";                              //数据库用户
    private static final String PASSWORD = "1";                             //数据库密码

    /*
    私有化构造方法,拒绝实例化
     */
    private ConnectionManager(){

    }
        /**
         * 获取数据库静态连接方法
         *
         * @return 数据库连接对象
         */

    public static Connection getConnection(){
        //定义数据库文件
        Connection conn = null;

        try {
            // 安装数据库驱动程序
            Class.forName(DRIVER);
            // 获取数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //返回数据库连接
        return conn;

    }
    /**
     * 关闭数据静态连接方法
     */
    public static void closeConnection(Connection conn){
        //判断数据库连接是否为空
        if (conn != null){
            try {
                // 判断连接是否未关闭
                if (!conn.isClosed()) {
                    // 关闭数据库连接
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        }
    
    public static void main(String[] args){
        //获取数据库连接
        Connection conn = getConnection();
        //判断数据库连接是否成功
        if(conn != null){
            JOptionPane.showMessageDialog(null,"恭喜,数据库连接成功!");

        }else{
            JOptionPane.showMessageDialog(null,"遗憾,数据库连接失败!");
        }
        //关闭数据库连接
        closeConnection(conn);
    }
}


When writing database code, the password and database name should be changed to the name used on your computer, and you must pay attention to the spelling of words! ! ! !

3. Test whether the connection is successful.
Insert picture description here
Finally, the prompt box as shown in the figure is displayed, which means success.

Query database

In order to better verify the successful connection of the database, a test package can be established to detect it
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_46705517/article/details/107077530