IDEA 链接Mysql数据库并执行查询操作的完整代码

 更新时间:2021年05月20日 10:26:33   作者:简简单单OnlineZuozuo  
这篇文章主要介绍了IDEA 链接Mysql数据库并执行查询操作的完整代码,代码不难,详细大家看完本文肯定有意向不到的收获,感兴趣的朋友跟随小编一起看看吧

 1、先写个 Mysql 的链接设置页面

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 谭健 on 2020/8/26. 星期三. 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 连接配置", 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(), "读取配置文件失败,配置文件不存在", NotificationType.ERROR);
        }
    }

}

2、然后简单的写个 JDBC 操作数据库的支持类

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 谭健 on 2020/8/12. 星期三. 17:42.
 * © All Rights Reserved.
 */
public class Mysql {


    /**
     * 执行查询语句的返回结果
     */
    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);
        }
    }


    // 参考: https://www.cnblogs.com/jyroy/p/9637149.html

    public static class JDBCUtil {


        /**
         * 执行sql 并返回 map 数据
         *
         * @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);

                // 基础信息
                ResultSetMetaData metaData = resultSet.getMetaData();
                // 返回了多少个字段
                int columnCount = metaData.getColumnCount();


                while (resultSet.next()) {
                    Map<String, Object> valueMap = new LinkedHashMap<>();
                    for (int i = 0; i < columnCount; i++) {
                        // 这个字段是什么数据类型
                        String columnClassName = metaData.getColumnClassName(i);
                        // 字段名称
                        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, "数据库连接成功", NotificationType.INFORMATION);
                }
            } catch (Exception e) {
                NotifyUtils.notifyUser(null, "数据库连接失败", 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 语句模版
     */
    public enum Template {

        SELECT("SELECT * FROM x WHERE 1 = 1 AND ", "SELECT * FROM {} WHERE 1 = 1 AND ", "查询语句"),
        UPDATE("UPDATE x SET x = x WHERE 1 = 1 AND ", "UPDATE {} SET x = x WHERE 1 = 1 AND ", "更新语句"),
        DELETE("DELETE FROM x WHERE 1 = 1 ", "DELETE FROM {} WHERE 1 = 1 ", "删除语句"),
        INSERT("INSERT INTO * (x) VALUES (x) ", "INSERT INTO {} (x) VALUES (x) ", "新增语句"),
        ;

        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;
        }

        /**
         * 模版内容:默认值
         */
        private final String defaultValue;
        /**
         * 动态内容
         */
        private final String dynamicValue;
        /**
         * 内容描述
         */
        private final String describe;


    }

}

3、写个测试连接的类&#xff0c;测试一下 mysql 是否可以正常链接

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 谭健 on 2020/9/15. 星期二. 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, "连接是正常的", NotificationType.INFORMATION);
            } else {
                NotifyUtils.notifyUser(null, "连接不正常", NotificationType.ERROR);
            }
            Mysql.JDBCUtil.closeRs(es);
        } catch (Exception e1) {
            e1.printStackTrace();
            NotifyUtils.notifyUser(null, "连接不正常", NotificationType.ERROR);
        }
    }
}

以上就是IDEA 链接Mysql数据库并执行查询操作的完整代码的详细内容,更多关于IDEA 链接Mysql执行查询操作 的资料请关注脚本之家其它相关文章!

相关文章

  • 详解mysql5.7密码忘记解决方法

    详解mysql5.7密码忘记解决方法

    这篇文章主要介绍了mysql5.7密码忘记解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05
  • 如何用cmd连接Mysql数据库

    如何用cmd连接Mysql数据库

    如何用cmd连接Mysql数据库,需要的朋友可以参考一下
    2013-03-03
  • 在大数据情况下MySQL的一种简单分页优化方法

    在大数据情况下MySQL的一种简单分页优化方法

    这篇文章主要介绍了在大数据情况下MySQL的一种简单分页优化方法,分页优化是MySQL优化的常用手段之一,需要的朋友可以参考下
    2015-05-05
  • MySQL中in和exists区别详解

    MySQL中in和exists区别详解

    最近在写SQL语句时,对选择IN 还是Exists犹豫不决,所以就上网查询了一下资料,本文就详细的介绍了两个方法的区别,感兴趣的可以了解一下
    2021-06-06
  • Idea 如何导入Mysql8.0驱动jar包

    Idea 如何导入Mysql8.0驱动jar包

    IDEA中的库(Libraries)就是用来存放外部jar包,我们的项目或模块需要某些jar包时,可以从这里把包导入到模块依赖(Dependencies)中,本文给大家介绍Idea 如何导入Mysql8.0驱动jar包,感兴趣的朋友一起看看吧
    2023-12-12
  • MySQL占用内存较大与CPU过高测试与解决办法

    MySQL占用内存较大与CPU过高测试与解决办法

    为了装mysql环境测试,装上后发现启动后MySQL占用内存了很大,达8百多兆。网上搜索了一下,得到高人指点my.ini。再也没见再详细的了..只好打开my.ini逐行的啃,虽然英文差了点,不过多少M还是看得明的
    2018-03-03
  • SQL更新与删除数据操作示例详解

    SQL更新与删除数据操作示例详解

    如果要在程序运行过程中操作数据库中的数据,那得先学会使用SQL语句,下面这篇文章主要给大家介绍了关于SQL查询语句更新和删除数据的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-01-01
  • 关于SqlServer中datediff用法

    关于SqlServer中datediff用法

    datediff是SQL SERVER里面的用法,ORACLE没有,主要作用是返回两个日期之间的时间间隔,本文通过实例代码给大家详细讲解,对datediff用法感兴趣的朋友跟随小编一起看看吧
    2022-11-11
  • Mysql如何解决1251 client does not support问题

    Mysql如何解决1251 client does not support问题

    这篇文章主要介绍了Mysql如何解决1251 client does not support问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • 一文了解MySQL二级索引的查询过程

    一文了解MySQL二级索引的查询过程

    索引是一种用于快速查询行的数据结构,就像一本书的目录就是一个索引,下面这篇文章主要给大家介绍了关于MySQL二级索引查询过程的相关资料,需要的朋友可以参考下
    2022-02-02

最新评论