我是使用c#编写visual studio的新手。我想将我的数据从visual studio连接到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);
}
}
}
答案 0 :(得分:0)
您需要在创建sql命令之前打开连接。 看来你永远不会调用你的SQLOpen方法,因此永远不会初始化和打开连接,因此你的insert语句失败了。
我建议为您的类创建一个构造函数并在其上调用open命令。
另外,不要忘记在运行命令后调用sqlClose()。