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


Posted in MySQL onMay 20, 2021

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

}

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

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数据库并执行查询操作的完整代码的详细内容,更多关于IDEA 链接Mysql执行查询操作 的资料请关注三水点靠木其它相关文章!

MySQL 相关文章推荐
多表查询、事务、DCL
Apr 05 MySQL
详解MySQL 联合查询优化机制
May 10 MySQL
新手必备之MySQL msi版本下载安装图文详细教程
May 21 MySQL
mysql中between的边界,范围说明
Jun 08 MySQL
MySQL中datetime时间字段的四舍五入操作
Oct 05 MySQL
Mysql排序的特性详情
Nov 01 MySQL
浅谈如何保证Mysql主从一致
Mar 13 MySQL
MySql重置root密码 --skip-grant-tables
Apr 11 MySQL
MySQL 数据库范式化设计理论
Apr 22 MySQL
MySQL数据库 任意ip连接方法
May 20 MySQL
MySQL count(*)统计总数问题汇总
Sep 23 MySQL
MySQL远程无法连接的一些常见原因总结
Sep 23 MySQL
MySQL 覆盖索引的优点
May 19 #MySQL
MySQL 视图(View)原理解析
超详细教你怎么升级Mysql的版本
详解mysql三值逻辑与NULL
MySQL时间盲注的五种延时方法实现
分析MySQL抛出异常的几种常见解决方式
详解MySQL数据库千万级数据查询和存储
May 18 #MySQL
You might like
如何实现给定日期的若干天以后的日期
2006/10/09 PHP
解析二进制流接口应用实例 pack、unpack、ord 函数使用方法
2013/06/18 PHP
详解WordPress中用于合成数组的wp_parse_args()函数
2015/12/18 PHP
php文件上传后端处理小技巧
2016/05/22 PHP
php使用PDO获取结果集的方法
2017/02/16 PHP
PHP实现倒计时功能
2020/11/16 PHP
用jquery实现学校的校历(asp.net+jquery ui 1.72)
2010/01/01 Javascript
Jquery异步请求数据实例代码
2011/12/28 Javascript
jquery交替变换颜色的三种方法 实例代码
2013/11/19 Javascript
七个很有意思的PHP函数
2014/05/12 Javascript
nodejs npm install全局安装和本地安装的区别
2014/06/05 NodeJs
Bootstrap基本组件学习笔记之面板(14)
2016/12/08 Javascript
使用mock.js随机数据和使用express输出json接口的实现方法
2018/01/07 Javascript
JavaScript代码实现txt文件的上传预览功能
2018/03/27 Javascript
JS中的两种数据类型及实现引用类型的深拷贝的方法
2018/08/12 Javascript
如何实现一个webpack模块解析器
2018/10/24 Javascript
react quill中图片上传由默认转成base64改成上传到服务器的方法
2019/10/30 Javascript
JavaScript设计模式--桥梁模式引入操作实例分析
2020/05/23 Javascript
jQuery 实现DOM元素拖拽交换位置的实例代码
2020/07/14 jQuery
Python中使用socket发送HTTP请求数据接收不完整问题解决方法
2015/02/04 Python
Python中的Descriptor描述符学习教程
2016/06/02 Python
python用pickle模块实现“增删改查”的简易功能
2017/06/07 Python
django项目搭建与Session使用详解
2018/10/10 Python
利用Pandas和Numpy按时间戳将数据以Groupby方式分组
2019/07/22 Python
Django对models里的objects的使用详解
2019/08/17 Python
python实现把二维列表变为一维列表的方法分析
2019/10/08 Python
解决django后台管理界面添加中文内容乱码问题
2019/11/15 Python
python os.path.isfile 的使用误区详解
2019/11/29 Python
html5中如何将图片的绝对路径转换成文件对象
2018/01/11 HTML / CSS
玲玲的画教学反思
2014/02/04 职场文书
高中生操行评语
2014/04/25 职场文书
工作失职检讨书
2015/01/26 职场文书
郭明义电影观后感
2015/06/08 职场文书
升学宴家长致辞
2015/07/27 职场文书
python爬取企查查企业信息之selenium自动模拟登录企查查
2021/04/08 Python
elasticSearch-api的具体操作步骤讲解
2021/06/28 Java/Android