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