Home > Java > Javagetting Started > How to connect to mysql database in java

How to connect to mysql database in java

王林
Release: 2020-06-03 16:40:22
forward
3118 people have browsed it

How to connect to mysql database in java

To connect to the mysql database, first we need to import the database driver jar package into the project, then create a Jdbc tool class, then write a method to obtain the database connection, and finally Determine whether the obtained Connection value is empty. If it is not empty, it means the connection has been successful.

Next let’s take a look at the specific code:

(Video tutorial recommendation: java video)

Jdbc tool class

package com.zwork.utils;

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

public class JdbcUtil {
    private static final String USER = "root";//用户
    private static final String PASSWORD = "root";//密码
    static final String DRIVER="com.mysql.jdbc.Driver";//数据库驱动
    static final String URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";//数据库地址

    private static Connection conn;

    //加载数据库驱动
    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接的方法
    public static Connection getConnection(){
        try {
            return conn = DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
Copy after login

Test code:

package com.zwork.test;

import com.zwork.utils.JdbcUtil;

import java.sql.Connection;

public class JdbcUtilTest {
    public static void main(String[] args) {
        Connection conn = JdbcUtil.getConnection();
        System.out.println(conn);
    }
}
Copy after login

Running results:

com.mysql.jdbc.Connection@5f8ed237
Copy after login

Recommended tutorial: java entry program

The above is the detailed content of How to connect to mysql database in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template