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

WeChat applet realizes multi-line text scrolling effect

This article example shares the specific code for...

JS+AJAX realizes the linkage of province, city and district drop-down lists

This article shares the specific code of JS+AJAX ...

Three ways to draw a heart shape with CSS

Below, we introduce three ways to draw heart shap...

How to use VLAN tagged Ethernet card in CentOS/RHEL system

In some scenarios, we want to assign multiple IPs...

Detailed introduction to logs in Linux system

Table of contents 1. Log related services 2. Comm...

Application of CSS3 animation effects in activity pages

background Before we know it, a busy year is comi...

JavaScript to achieve all or reverse selection function

This article shares the specific code of JavaScri...

Introduction to Linux compression and decompression commands

Table of contents Common compression formats: gz ...

How to reduce the root directory of XFS partition format in Linux

Table of contents Preface System environment Curr...

Native js encapsulation seamless carousel function

Native js encapsulated seamless carousel plug-in,...