zhongrj
2024-02-23 fc47a705ab33a976f7a116c0ce6e236bb5057fa5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package org.springblade.binlog.client;
 
import lombok.extern.slf4j.Slf4j;
import org.springblade.binlog.constant.BinLogConstants;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
/**
 * mysql 客户端连接
 */
@Slf4j
@Component
public class MysqlClient {
 
    //声明对象
    private static MysqlClient mysqlClient;
 
 
    @Resource
    private BinLogConstants binLogConstants;
 
    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        mysqlClient = this;
        mysqlClient.binLogConstants = this.binLogConstants;
    }
 
    /**
     * sql 连接
     * @param sql
     */
    public static void sqlConnect(String sql,Integer type){
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = mysqlClient.binLogConstants.getFromUrl();
        String user = mysqlClient.binLogConstants.getFromUsername();
        String password = mysqlClient.binLogConstants.getFromPassword();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName ( driver );
            conn = (Connection) DriverManager.getConnection ( url, user, password );
            if (!conn.isClosed ()) {
                log.info( "数据库连接成功!" );
                ps = conn.prepareStatement ( sql );
                //判断是否为修改,删除
                if (type==1){
                    //修改删除
                    ps.executeUpdate();
                    log.info( "数据已发送成功!" );
                }else {
                    //新增
                    ps.execute();
                    log.info( "数据已发送成功!" );
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace ();
        }finally {
            try {
                ps.close();
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
 
    /**
     * 连接mysql数据库 新增
     * @param sql
     */
    public static void insert(String sql) {
        sqlConnect(sql,2);
    }
 
    /**
     * 连接mysql数据库 修改
     * @param sql
     */
    public static void update(String sql) {
        sqlConnect(sql,1);
    }
 
    /**
     * 连接mysql数据库 删除
     * @param sql
     */
    public static void delete(String sql) {
        sqlConnect(sql,1);
    }
}