IDEA complete code to connect to MySQL database and perform query operations

IDEA complete code to connect to MySQL database and perform query operations

1. Write a Mysql link setting page first

package com.wretchant.fredis.menu.mysql;

import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.wretchant.fredis.gui.dialog.TableDialog;
import com.wretchant.fredis.util.NotifyUtils;
import com.wretchant.fredis.util.PropertiesUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.Map;
import java.util.Properties;

/**
 * @author Created by Tan Jian on 2020/8/26. Wednesday. 15:24.
 * © All Rights Reserved.
 */
public class MysqlConfig extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {

        Properties properties = PropertiesUtils.readFromSystem();
        if (properties != null) {
            TableDialog.TableField build = TableDialog.TableField.build(properties.stringPropertyNames());
            TableDialog dialog = new TableDialog("Mysql connection configuration", build);
            for (int i = 0; i < dialog.getLabels().size(); i++) {
                JLabel label = dialog.getLabels().get(i);
                JTextField textField = dialog.getInputs().get(i);
                String property = properties.getProperty(label.getText());
                textField.setText(property);
            }
            dialog.show();
            if (dialog.isOK()) {
                Map<String, String> valueMap = dialog.getValueMap();
                valueMap.forEach(properties::setProperty);
                PropertiesUtils.write2System(properties);
            }
        } else {
            NotifyUtils.notifyUser(event.getProject(), "Failed to read configuration file, configuration file does not exist", NotificationType.ERROR);
        }
    }

} 

2. Then simply write a JDBC support class for operating the database

package com.wretchant.fredis.support;

import cn.hutool.core.util.StrUtil;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.SelectionModel;
import com.wretchant.fredis.util.ClipboardUtils;
import com.wretchant.fredis.util.NotifyUtils;
import com.wretchant.fredis.util.PropertiesUtils;
import com.wretchant.fredis.value.StringValue;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.sql.*;
import java.util.*;

/**
 * @author Created by Tan Jian on 2020/8/12. Wednesday. 17:42.
 * © All Rights Reserved.
 */
public class Mysql {


    /**
     * Execute the query statement to return the result */
    public static class Rs {

        public Rs(List<Map<String, Object>> r) {
            this.r = r;
            this.count = r.size();
        }

        private List<Map<String, Object>> r = new ArrayList<>();

        private int count;

        public List<Map<String, Object>> getR() {
            return r;
        }

        public void setR(List<Map<String, Object>> r) {
            this.r = r;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public Map<String, Object> one() {
            if (Objects.isNull(r) || r.isEmpty()) {
                return null;
            }
            return r.get(0);
        }


        public Object oneGet(String key) {
            return one().get(key);
        }
    }


    // Reference: https://www.cnblogs.com/jyroy/p/9637149.html

    public static class JDBCUtil {


        /**
         * Execute sql and return map data *
         * @param sql
         * @return
         */
        public static Rs rs(String sql) {
            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;
            List<Map<String, Object>> r = new ArrayList<>();
            try {
                connection = Mysql.DatabaseUtils.getConnection();
                statement = connection.createStatement();
                resultSet = statement.executeQuery(sql);

                // Basic information ResultSetMetaData metaData = resultSet.getMetaData();
                // How many fields are returned int columnCount = metaData.getColumnCount();


                while (resultSet.next()) {
                    Map<String, Object> valueMap = new LinkedHashMap<>();
                    for (int i = 0; i < columnCount; i++) {
                        // What data type is this field? String columnClassName = metaData.getColumnClassName(i);
                        //Field name String columnName = metaData.getColumnName(i);
                        Object value = resultSet.getObject(columnName);
                        valueMap.put(columnName, value);
                    }
                    r.add(valueMap);
                }
            } catch (Exception e1) {
                NotifyUtils.notifyUser(null, "error", NotificationType.ERROR);
                e1.printStackTrace();
            finally
                release(connection, statement, resultSet);
            }
            return new Rs(r);
        }

        public static ResultSet es(String sql) {
            Connection connection;
            Statement statement;
            ResultSet resultSet = null;
            try {
                connection = Mysql.DatabaseUtils.getConnection();
                statement = connection.createStatement();
                resultSet = statement.executeQuery(sql);
            } catch (Exception e1) {
                NotifyUtils.notifyUser(null, "error", NotificationType.ERROR);
                e1.printStackTrace();
            }
            return resultSet;
        }


        public static void release(Connection connection, Statement st, ResultSet rs) {
            closeConn(connection);
            closeRs(rs);
            closeSt(st);
        }

        public static void closeRs(ResultSet rs) {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            finally
                rs = null;
            }
        }

        private static void closeSt(Statement st) {
            try {
                if (st != null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            finally
                st = null;
            }
        }

        private static void closeConn(Connection connection) {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            finally
                connection = null;
            }
        }

    }

    public static class DatabaseUtils {
        private static Connection connection = null;

        static {
            Properties properties = PropertiesUtils.readFromSystem();
            try {
                if (properties != null) {
                    Class.forName("com.mysql.cj.jdbc.Driver");
                    connection = DriverManager.getConnection(
                            properties.getProperty("mysql.url"),
                            properties.getProperty("mysql.username"),
                            properties.getProperty("mysql.password")
                    );
                    NotifyUtils.notifyUser(null, "Database connection successful", NotificationType.INFORMATION);
                }
            } catch (Exception e) {
                NotifyUtils.notifyUser(null, "Database connection failed", NotificationType.ERROR);
                e.printStackTrace();
            }
        }

        public static Connection getConnection() {
            return connection;
        }
    }


    public static void exec(@NotNull AnActionEvent event, Template template) {
        StringValue stringValue = new StringValue(template.getDefaultValue());
        Optional.ofNullable(event.getData(PlatformDataKeys.EDITOR)).
                ifPresent(editor -> {
                    SelectionModel selectionModel = editor.getSelectionModel();
                    String selectedText = selectionModel.getSelectedText();
                    if (StringUtils.isNotBlank(selectedText)) {
                        stringValue.setValue(StrUtil.format(template.getDynamicValue(), selectedText));
                    }
                });
        ClipboardUtils.clipboard(stringValue.getValue());
        NotifyUtils.notifyUser(event.getProject(), stringValue.getValue(), NotificationType.INFORMATION);
    }

    /**
     * sql statement template */
    public enum Template {

        SELECT("SELECT * FROM x WHERE 1 = 1 AND ", "SELECT * FROM {} WHERE 1 = 1 AND ", "Query statement"),
        UPDATE("UPDATE x SET x = x WHERE 1 = 1 AND ", "UPDATE {} SET x = x WHERE 1 = 1 AND ", "Update statement"),
        DELETE("DELETE FROM x WHERE 1 = 1 ", "DELETE FROM {} WHERE 1 = 1 ", "delete statement"),
        INSERT("INSERT INTO * (x) VALUES (x) ", "INSERT INTO {} (x) VALUES (x) ", "New statement"),
        ;

        Template(String defaultValue, String dynamicValue, String describe) {
            this.defaultValue = defaultValue;
            this.dynamicValue = dynamicValue;
            this.describe = describe;
        }

        public String getDynamicValue() {
            return dynamicValue;
        }

        public String getDefaultValue() {
            return defaultValue;
        }

        public String getDescribe() {
            return describe;
        }

        /**
         * Template content: default value*/
        private final String defaultValue;
        /**
         * Dynamic content */
        private final String dynamicValue;
        /**
         * Description */
        private final String describe;


    }

}

3. Write a test connection class to test whether mysql can connect normally

package com.wretchant.fredis.menu.mysql;

import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.wretchant.fredis.support.Mysql;
import com.wretchant.fredis.util.NotifyUtils;
import org.jetbrains.annotations.NotNull;

import java.sql.ResultSet;

/**
 * @author Created by Tan Jian on 2020/9/15. Tuesday. 10:17.
 * © All Rights Reserved.
 */
public class MysqlConn extends AnAction {


    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        try {
            ResultSet es = Mysql.JDBCUtil.es("select 1 as ct");
            es.next();
            int ct = es.getInt("ct");
            if (ct == 1) {
                NotifyUtils.notifyUser(null, "The connection is normal", NotificationType.INFORMATION);
            } else {
                NotifyUtils.notifyUser(null, "Connection is abnormal", NotificationType.ERROR);
            }
            Mysql.JDBCUtil.closeRs(es);
        } catch (Exception e1) {
            e1.printStackTrace();
            NotifyUtils.notifyUser(null, "Connection is abnormal", NotificationType.ERROR);
        }
    }
} 

The above is the details of the complete code of IDEA connecting to MySQL database and executing query operations. For more information about IDEA connecting to MySQL to execute query operations, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Tips for viewing Java source code using Intellij IDEA
  • IntelliJ IDEA Tips for Using Bookmarks
  • Detailed explanation of common errors and usage tips for creating projects using Maven in IDEA (recommended)
  • IntelliJ IDEA plug-in EasyCode installation method and usage tips
  • IntellJ IDEA Artifact Usage Tips (Summary)
  • Use Intellij Idea to connect to the remote server to realize remote upload and deployment function
  • How to quickly connect Phoenix using the IDEA graphical interface
  • How to control the function icon ICON on the left side of the editor in IDEA (operation steps)
  • Strongly recommend these IDEA usage tips to improve code efficiency

<<:  What does this.parentNode.parentNode (parent node of parent node) mean?

>>:  JavaScript in-depth analysis of the direction of this and how to modify the direction

Recommend

How to make vue long list load quickly

Table of contents background Main content 1. Comp...

A very detailed summary of communication between Vue components

Table of contents Preface 1. Props, $emit one-way...

How to configure jdk environment under Linux

1. Go to the official website to download the jdk...

MySQL 8.0.21.0 Community Edition Installation Tutorial (Detailed Illustrations)

1. Download MySQL Log in to the MySQL official we...

MySQL isolation level detailed explanation and examples

Table of contents 4 isolation levels of MySQL Cre...

Detailed explanation of the use of bus in Vue

Vue bus mechanism (bus) In addition to using vuex...

Copy and paste is the enemy of packaging

Before talking about OO, design patterns, and the ...

Install Zookeeper under Docker (standalone and cluster)

After starting Docker, let's take a look at t...

Setting up shared folders in Ubuntu virtual machine of VMWare14.0.0

This is my first blog post. Due to time constrain...

Deploy Confluence with Docker

1. Environmental requirements 1. Docker 17 and ab...

An article to teach you HTML

If you are not committed to becoming an artist, t...

Commonplace talk about MySQL event scheduler (must read)

Overview MySQL also has its own event scheduler, ...

First experience of creating text with javascript Three.js

Table of contents Effect Start creating text Firs...

Page Refactoring Skills - Content

Enough of small talk <br />Based on the lar...