// 公共增删方法
using MySql.Data.MySqlClient;
using System.Data;
namespace ******
{
public class MySQLHelper
{
private MySqlConnection conn = null;
private MySqlCommand comm = null;
private MySqlDataReader reader = null;
/// <summary>
/// 构造方法里建议连接
/// </summary>
/// <param name="connStr"></param>
public MySQLHelper(string connStr)
{
conn = new MySqlConnection(connStr);
}
/// <summary>
/// 发送指令
/// </summary>
/// <param name="sql"></param>
public void CreateCommand(string sql)
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
comm = new MySqlCommand(sql, conn);
}
/// <summary>
/// 增删改公共方法
/// </summary>
/// <returns></returns>
public int commonExecute()
{
int res;
res = comm.ExecuteNonQuery();
conn.Close();
return res;
}
/// <summary>
/// 查询方法
/// </summary>
/// <returns></returns>
public DataTable selectExecute()
{
DataTable dt = new DataTable();
using (reader = comm.ExecuteReader(CommandBehavior.CloseConnection))
{
dt.Load(reader);
}
return dt;
}
}
}
// 代码中引用
using Sunny.UI;
using System.Threading;
using System.IO.Ports;
using System;
using System.Data;
string connStr = "Database=db_oxygen_check;Data Source=127.0.0.1;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306;";
private void SystemSettingForm_Load(object sender, EventArgs e)
{
// 获取可用串口、将串口名称回显到页面上
string[] portNames = SerialPort.GetPortNames();
foreach (string portName in portNames)
{
uiComboBox2.Items.Add(portName);
}
if (uiComboBox2.Items.Count > 0)
{
uiComboBox2.SelectedIndex = 0;
MySQLHelper mySQLHelper = new MySQLHelper(connStr);
string sql = "select * from tb_system_settings";
mySQLHelper.CreateCommand(sql);
DataTable dataTable = mySQLHelper.selectExecute();
if (dataTable.Rows.Count > 0)
{
txt_plcCom.Text = dataTable.Rows[0]["plc_com"].ToString();
uiComboBox2.Text = dataTable.Rows[0]["oxygen_com"].ToString();
}
}
}
// 按钮选中串口号和地址
private void uiButton1_Click(object sender, EventArgs e)
{
string plcCom = txt_plcCom.Text;
string oxygenCom = uiComboBox2.Text;
if (plcCom.Trim().Length == 0)
{
UIMessageBox.ShowError("请选择正确的PLC IP地址");
return;
}
if (oxygenCom.Trim().Length == 0)
{
UIMessageBox.ShowError("请选择正确的***串口号");
return;
}
string sql = "update tb_system_settings set plc_com = '" + plcCom + "', oxygen_com = '" + oxygenCom + "' where id = 1";
MySQLHelper mySQLHelper = new MySQLHelper(connStr);
mySQLHelper.CreateCommand(sql);
int res = mySQLHelper.commonExecute();
if (res > 0)
{
UIMessageBox.ShowSuccess("设置成功!");
DialogResult = System.Windows.Forms.DialogResult.OK;
Thread thread = new Thread(new ParameterizedThreadStart(logWrite));
OperateLog op = new OperateLog();
op.operateType = 2;
op.adminId = LoginDataStatic.id;
op.adminName = LoginDataStatic.name;
op.operageDesc = "修改系统设定为:{PLC串口号: " + plcCom + ", ***串口号: " + oxygenCom + "}";
op.createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
thread.Start(op);
}
else
{
UIMessageBox.ShowError("设置失败!");
DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
}