Teach you to connect to MySQL database using eclipse

Teach you to connect to MySQL database using eclipse

Preface

Since errors always occur, record the process of connecting to the MySQL database.

Connection Process

1. Download MySQL and install it. The version here is 8.0.18

2. Download MySQL jdbc, unzip it after downloading, and save it in the MySQL directory for easy searching

insert image description here
insert image description here
insert image description here

3. Connect to the database

(1) In Eclipse, select Window-preferences-java-Build Path-User Libraries

insert image description here

(2) Click the new button on the right.

insert image description here

(3) Enter jdbc here, check the box, and click OK

insert image description here

(4) Return to the previous level interface, click Add External JARs, open the directory where your jdbc is stored, and click Open-ok.

insert image description here

(5) Next, import the jar package into the project. Right-click the project and select Build Path-Configure Build Path.

insert image description here

(6) Click Add Library… -User Library-Next on the right. Check the box and click Finish

insert image description here

(7) Return to the previous level interface and you will see the jdbc you added. Click Apply and then click OK.

insert image description here

(8) Then you can see the jdbc you imported in your project

insert image description here

4. Create a new package linkMysql under Java resources in the project, and create a new class Demo in it

The code is as follows:

package linkMysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo {
    // Load the database driver com.mysql.jdbc.Driver
        private static String dbdriver = "com.mysql.cj.jdbc.Driver"; //Because MySQL is version 8.0, you need to add cj. If it is version 5.0, you don't need it. // Get the mysql connection address private static String dburl = "jdbc:mysql://127.0.0.1:3306/cmxDatabaseName?&useSSL=false&serverTimezone=UTC";  
        		//&serverTimezone=UTC here is very important, this is the reason why I got an error before //Data name private static String username = "root";
        // Database passwordprivate static String userpassword = "123456";
        // Get a data connection public static Connection conn = null;
        // Get a connection status // The following is an example, where database1 is the database name, followed by a query statement public static void main(String[] args) throws SQLException {
            List<List<Object>> x = getData("database1",
                    "select * from students");
            System.out.println(x);
        }

    /**
     * Get database connection * 
     * @param myProjName
     * @return
     */
    private static Connection getConn(String myProjName) {
        Connection conn = null;
        try {
            Class.forName(dbdriver);            
            String myjdbcUrl = dburl.replace("cmxDatabaseName", myProjName);
            conn = DriverManager.getConnection(myjdbcUrl, username, userpassword);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * Close the database connection * 
     * @param rs
     * @param ps
     * @param conn
     */
    private static void closeAll(ResultSet rs, PreparedStatement ps,
            Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn == null)
            return;
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Look up a table and return a list of rows, each of which contains a list of columns.
     * 
     * @param ProjName
     * @param sql
     * @return
     */
    public static List<List<Object>> getData(String ProjName, String sql) {
        Connection conn = getConn(ProjName);
        PreparedStatement ps = null;
        List<List<Object>> list = new ArrayList<List<Object>>();
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            while (rs.next()) {
                List<Object> lst = new ArrayList<Object>();
                for (int i = 1; i <= columnCount; ++i) {
                    lst.add(rs.getObject(i) == null ? "" : rs.getObject(i));
                }
                list.add(lst);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        finally
            closeAll(rs, ps, conn);
        }
        return list;
    }
}

5. Run the class as a Java application and you can see all the information in the students table in the console.

insert image description here

This is the end of this article about teaching you how to connect MySQL database with Eclipse. For more information about connecting MySQL database with Eclipse, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Connecting to MySQL database in C++ in Eclipse
  • Example code for connecting to MySQL database in myeclipse
  • Myeclipse connect to mysql database experience
  • MyEclipse connects to MySQL database graphic tutorial
  • Summary of Eclipse connecting to Mysql database
  • How to connect MyEclipse to MySQL database (I)
  • How to connect to MySQL database using Eclipse
  • Steps to connect to MySQL database using Eclipse
  • Solution to error when connecting MyEclipse to MySQL database
  • Basic introduction to connecting MyEclipse to MySQL database via JDBC

<<:  JavaScript to achieve simple drag effect

>>:  Project practice of deploying Docker containers using Portainer

Recommend

How to install and uninstall open-vswitch in Linux

1. Compile and install ovs from source code: Inst...

Implementation of element multiple form validation

In the project, form testing is often encountered...

Detailed tutorial on installing and using Kong API Gateway with Docker

1 Introduction Kong is not a simple product. The ...

Vue makes div height draggable

This article shares the specific code of Vue to r...

Detailed explanation of the MySQL MVCC mechanism principle

Table of contents What is MVCC Mysql lock and tra...

How to design MySQL statistical data tables

Table of contents Is real-time update required? M...

Analysis of Docker's method for creating local images

The so-called container actually creates a readab...

Solve the problem of mysql data loss when docker restarts redis

Official documentation: So mysql should be starte...

Meta viewport makes the web page full screen display control on iPhone

In desperation, I suddenly thought, how is the Sin...

MySQL database monitoring software lepus usage problems and solutions

When using lepus3.7 to monitor the MySQL database...

Mysql database master-slave separation example code

introduce Setting up read-write separation for th...

Ubuntu 20.04 sets a static IP address (including different versions)

Because Ubuntu 20.04 manages the network through ...