我正在尝试使用Asp.Net将数据插入MYSQL数据库但是我收到以下错误消息:由于System.InvalidOperationsException而无法连接到数据库。连接必须有效并且打开。 这就是我在做的事情:
protected void SU_Button_Click(object sender, EventArgs e)
{
string connectionString = @"Data Source=mno; Database=xyz; User ID=abc; Password=abc";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
string insertData = "insert into signup_table(firstname,surname,mobile_number,email_address,password," +
"confirm_password) values (@F_Name, @S_Name, @M_Number, @E_Address, @Password, @C_Password)";
MySqlCommand command = new MySqlCommand(insertData, connection);
command.Parameters.AddWithValue("@F_Name",FN_TextBox.Text);
command.Parameters.AddWithValue("@S_Name", SN_TextBox.Text);
command.Parameters.AddWithValue("@M_Number", MN_TextBox.Text);
command.Parameters.AddWithValue("@E_Address", EA_TextBox.Text);
command.Parameters.AddWithValue("@Password", P_TextBox.Text);
command.Parameters.AddWithValue("@C_Password", CP_TextBox.Text);
int result = command.ExecuteNonQuery();
connection.Open();
MessageBox.Show("Connected to database");
MessageBox.Show("Data inserted successfully");
}
catch(Exception ex)
{
MessageBox.Show("Failed to connect to database due to" + ex.ToString());
MessageBox.Show("Failed to insert data due to" + ex.ToString());
}
}
}
请提出建议。在此先感谢... :)
答案 0 :(得分:1)
您必须在执行查询之前打开连接。
connection.Open();
int result = command.ExecuteNonQuery();
完成后也不要忘记关闭你的连接。
答案 1 :(得分:0)
更改此
int result = command.ExecuteNonQuery();
connection.Open();
到这个
connection.Open();
int result = command.ExecuteNonQuery();