首页 > 数据库 >java直连mysql操作数据

java直连mysql操作数据

时间:2024-02-04 10:31:58浏览次数:36  
标签:直连 preparedStatement java String setString private final mysql id

连接器

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * @author : chenKeFeng
 * @date : 2024/1/30 10:21
 */
public class MySQLConnector {
    
    private final String url;
    private final String userName;
    private final String passWord;

    public MySQLConnector(String url, String username, String password) {
        this.url = url;
        this.userName = username;
        this.passWord = password;
    }

    public Connection connect() throws SQLException {
        return DriverManager.getConnection(url, userName, passWord);
    }

    public ResultSet executeQuery(Connection connection, String query) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(query);
        return preparedStatement.executeQuery();
    }

    public void close(Connection connection) throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }
}

 

这里演示把用户的数据迁移到另一个数据库

定义变量

//用户默认头像
    private static final String AVATAR = "xxx";
    //crm用户数据库
    private static final String URL = "jdbc:mysql://xxx:3306/user";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "xxx";

    //渠道数据库
    private static final String URL2 = "jdbc:mysql://xxx:3306/channel";
    private static final String USERNAME2 = "root";
    private static final String PASSWORD2 = "xxx";

    //需要变更到部门的部门id
    private static final String DEPTID = "xxx";
    //变更的部门初始化权值
    private static final BigDecimal INITVALUE = new BigDecimal("xxx");

    //角色id
    private static final String ROLEID = "xxx";
    private static final String ROLEName = "xxx";

 

原始方法实现crud

public static void main(String[] args) {
        MySQLConnector connector = new MySQLConnector(URL, USERNAME, PASSWORD);
        MySQLConnector connector2 = new MySQLConnector(URL2, USERNAME2, PASSWORD2);
        try {
            Connection connection = connector.connect();
            Connection connection2 = connector2.connect();

            String query = "SELECT sui.id, sui.user_name, sui.phone_number FROM sys_user_info as sui join sys_staff_info as ssi on ssi.user_id = sui.id where ssi.user_type in(0, 2, 3) and ssi.deleted =0 and ssi.status in (0, 3) and sui.is_deleted = 0";
            ResultSet resultSet = connector.executeQuery(connection, query);

            List<CrmUserVo> userList = new ArrayList<>();
            //boolean numberExists = false;
            while (resultSet.next()) {
                CrmUserVo crmUserVo = new CrmUserVo();
                String id = resultSet.getString("id");
                String name = resultSet.getString("user_name");
                String mobile = resultSet.getString("phone_number");

                crmUserVo.setId(id);
                crmUserVo.setUserName(name);
                crmUserVo.setMobile(mobile);
                System.out.println("crm用户:" + crmUserVo);
                //查询渠道用户是否存在
                String sql1 = "SELECT COUNT(*) FROM channel_user WHERE phone_number = ? and deleted =0";
                PreparedStatement preparedStatement = connection2.prepareStatement(sql1);
                preparedStatement.setString(1, mobile);
                try (ResultSet result = preparedStatement.executeQuery()) {
                    if (result.next()) {
                        int count = result.getInt(1);
                        if (count == 0) {
                            //numberExists = true;
                            userList.add(crmUserVo);
                        }
                    }
                }
            }
            System.out.println("过滤后的数据条数" + userList.size());

            for (CrmUserVo crmUserVo : userList) {
                //获取部门详情
                Dept dept = new Dept();
                String deptSql = "SELECT * FROM sys_department_info WHERE id = ?";
                PreparedStatement deptPreparedStatement = connection2.prepareStatement(deptSql);
                deptPreparedStatement.setString(1, DEPTID);
                try (ResultSet results = deptPreparedStatement.executeQuery()) {
                    if (results.next()) {
                        String deptId = results.getString("id");
                        String deptName = results.getString("depart_name");
                        BigDecimal maxPowerNum = results.getBigDecimal("max_power_num");
                        Integer level = results.getInt("level");
                        String companyId = results.getString("company_id");
                        dept.setId(deptId);
                        dept.setDepartName(deptName);
                        dept.setMaxPowerNum(maxPowerNum);
                        dept.setLevel(level);
                        dept.setCompanyId(companyId);
                    }
                }
                
                BigDecimal maxValue = dept.getMaxPowerNum().add(INITVALUE);
                String insertQuery = "INSERT INTO channel_user (id, user_name, phone_number, avatar, invite_code, create_time, date_join, company_id, depart_id, status, power_num) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                PreparedStatement preparedStatement = connection2.prepareStatement(insertQuery);
                String channelUserId = UUIDutils.getUUID32();
                preparedStatement.setString(1, channelUserId);
                preparedStatement.setString(2, crmUserVo.getUserName());
                preparedStatement.setString(3, crmUserVo.getMobile());
                preparedStatement.setString(4, AVATAR);
                preparedStatement.setString(5, createChannelUserInvite());
                preparedStatement.setTimestamp(6, Timestamp.valueOf(LocalDateTime.now()));
                preparedStatement.setDate(7, Date.valueOf(LocalDate.now()));
                preparedStatement.setString(8, dept.getCompanyId());
                preparedStatement.setString(9, dept.getId());
                preparedStatement.setInt(10, 0);
                preparedStatement.setBigDecimal(11, maxValue);
                int rowsAffected = preparedStatement.executeUpdate();
                System.out.println("插入用户数据:" + rowsAffected);

                if (rowsAffected > 0) {
                    //新增渠道用户和角色绑定关联
                    String insertRole = "INSERT INTO union_role_user (id, user_id, role_id, role_name) VALUES (?, ?, ?, ?)";
                    PreparedStatement rolePreparedStatement = connection2.prepareStatement(insertRole);
                    rolePreparedStatement.setString(1, UUIDutils.getUUID32());
                    rolePreparedStatement.setString(2, channelUserId);
                    rolePreparedStatement.setString(3, ROLEID);
                    rolePreparedStatement.setString(4, ROLEName);
                    int roleRows = rolePreparedStatement.executeUpdate();
                    System.out.println("插入角色" + roleRows);

                    //修改部门权值
                    String updateSql = "UPDATE sys_department_info SET max_power_num = ? WHERE id = ?";
                    try (PreparedStatement updatePreparedStatement = connection2.prepareStatement(updateSql)) {
                        updatePreparedStatement.setBigDecimal(1, maxValue);
                        updatePreparedStatement.setString(2, dept.getId());

                        int rowsAffected1 = updatePreparedStatement.executeUpdate();
                        System.out.println("修改部门权值: " + rowsAffected1);
                    }
                }
            }
            connector.close(connection);
            connector2.close(connection2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

 



标签:直连,preparedStatement,java,String,setString,private,final,mysql,id
From: https://blog.51cto.com/u_15466961/9578297

相关文章

  • JAVA Spring Boot快速开始
    实践环境SpringBoot3.2.1Maven3.8.8JDK1.8.0_331创建项目通过http://start.spring.io/网站创建包含SpringBoot的项目,具体如下:点击GENERATE按钮后,会自动生成并下载SpringBootQuickStartDemo.zip导入项目解压述下载的项目压缩包,解压后的项目文件结构如下:E:codeProjects\Sprin......
  • iText PDF Java API 入门介绍教程
    ​ iText是一个非常强大的Java库,用于创建和操作PDF文档。可以在Java应用程序中生成PDF文档,包括文本、表格、图像等丰富的内容。iText具有强大的功能,如PDF/A、数字签名、加密等,适用于复杂的PDF处理需求。iText是一个非常灵活和强大的库,可以根据具体需求进行大量的定制和扩展。......
  • Java浅谈BufferedReader
    既然Scanner简单好用,为什么要用BufferedReader呢?主要原因是面对大量的读入显得较慢且不安全,这里体现在三个方面,一方面是解析的问题,好用意味着封装的更复杂,一拖n的接口解析起来会慢;另一方面是缓冲区的问题,Scanner缓冲区小1024B,直面物理介质的机会更大,众所周知,IO时间在大数据面前......
  • java面向对象基础语法之成员变量和局部变量的区别(详细)
    一:概述在面向对象一开始的学习中,对一些其中基础语法的了解和熟悉非常的重要,有助于更深入的去学习面向对象的知识。在这里具体的说明一下成员变量和局部变量的区别。二:具体说明<1>java中变量的分类<2>成员变量和局部变量的定义说明。成员变量:成员变量分为静态变量(类变量)和实例变量......
  • 【Java基础】BlockingQueue及其子类
    ArrayBlockingQueue(数组实现的有界阻塞队列)特点:基于数组的有界阻塞队列,按先进先出(FIFO)原则排序元素。可以选择公平性(即按线程等待的先后顺序访问队列)或非公平性,默认是非公平的。用途:适用于需要固定大小的队列场景。LinkedBlockingQueue(链表实现的阻塞队列)特点:基于链表的可选边界(有......
  • pid文件未生成:mysqld_safe mysqld from pid file /usr/local/mysql/data/mysql.pid en
    问题/usr/local/mysql/bin/mysqld_safe--defaults-file=/usr/local/mysql/conf/my.cnf--user=mysql该命令启动mysql时,未启动成功,终端输出下列报错:2024-02-03T02:56:51.449040Zmysqld_safeLoggingto'/usr/local/mysql/mysqllog/logfile/mysql-err.log'.2024-02-03T02:......
  • 支付宝直连商户处理支付交易投诉管理,支持多商户
    大家好,我是小悟1、问题背景玩过支付宝生态的,或许就有这种感受,如果收到投诉单,不会通知到手机端,只会在支付宝商家后台-账号中心-安全中心-消费者投诉-支付交易投诉那里显示。那你能一直盯着电脑看吗?可能当你有空打开电脑登录查看的时候,已经积累了好多超时未处理的投诉单。一旦处理不......
  • 地铁最优线路算法的求解(三)-深度优先搜索java实现
    多的不说,showmethecode,先上一段java代码1/*2*深度优先算法(DFS)算法生成所有可能路径3*startId:出发站4*endId:到达站5*graph:辅助邻接矩阵,若99站与35站相邻,6*则graph[35][99]=1,graph[99][35]=17*8*......
  • Java套接字编程学习
    一、前言Java套接字编程用于不同JRE上运行的应用程序之间进行通信,可以是面向连接或无连接的。Socket类和ServerSocket类用于面向连接的套接字编程,DatagramSocket类和DatagramPacket类用于无连接的套接字编程。我们需要根据服务器IP地址和端口号来区分套接字。Socket类用于客户端和......
  • Java生成微信小程序二维码的方式有哪些?
    大家好我是咕噜美乐蒂,很高兴又见面啦!今天我们来谈一下如何使用Java生成微信小程序二维码,有哪些方式方法呢?生成微信小程序二维码是开发微信小程序时的常见需求之一。在Java中,我们可以使用多种方式来生成微信小程序二维码。本文将为您介绍几种常用的方式。一、使用第三方库1.zxingzxi......