我是visual studio c#编程新手。我想将我的数据从visualstudio连接到mysql数据库。我使用xampp作为服务器,但是当我尝试连接时,它会给出错误消息:“连接必须有效并且打开”。我不知道怎么修。我试过一些方法来解决这个问题,但仍然没有解决。
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace scadaSql
{
public partial class Form1 : Form
{
MySqlConnection connectionMySql;
bool statusServer = false;
string server = "localhost";
string database = "topsus_iot";
string uid = "root";
string pass = "";
string conString;
int checkCounter = 0;
int timeCounter = 0;
int filesCnt = 0;
int loopProg = 0;
public void sqlInsert(int temp, int humidity)
{
try
{
MySqlCommand cmd = connectionMySql.CreateCommand();
cmd.CommandText = "INSERT INTO data (device_id, temperature, humidity) VALUE(2, @temp, @humidity)";
cmd.Parameters.AddWithValue("@temp", temp);
cmd.Parameters.AddWithValue("@humidity", humidity);
cmd.ExecuteNonQuery();
}
catch (Exception X)
{
MessageBox.Show(X.Message);
throw;
}
}
public bool sqlClose()
{
try
{
connectionMySql.Close();
label4.Text = "disconnected";
label4.ForeColor = System.Drawing.Color.Lime;
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public bool sqlOpen()
{
try
{
connectionMySql.Open();
label4.Text = "Connected";
label4.ForeColor = System.Drawing.Color.Lime;
return true;
}
catch (MySqlException mx)
{
switch (mx.Number)
{
case 0:
break;
case 1045:
break;
}
return false;
}
}
public Form1()
{
InitializeComponent();
conString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + pass + ";";
connectionMySql = new MySqlConnection(conString);
}
private void Form1_Load(object sender, EventArgs e)
{
statusServer = false;
sqlOpen();
}
private void button1_Click(object sender, EventArgs e)
{
sqlInsert((int)temperature.Value, (int)humidity.Value);
}
}
}
1条答案
按热度按时间liwlm1x91#
在创建sql命令之前,需要打开连接。似乎您从未调用sqlopen方法,因此连接从未初始化和打开,因此insert语句失败。
我建议为类创建一个构造函数并对其调用open命令。
还有,唐´别忘了在您之后调用sqlclose()´我们执行完命令了。