我正在尝试将值添加到数据库中,但每次我尝试添加某些内容时,我会在ExecuteNonQuery()
中收到错误消息" 连接必须有效且。开放"
而且我不知道该怎么办!!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ClientesClinica
{
public partial class frmCadastro : Form
{
MySqlConnection conect = new MySqlConnection("server = localhost; user id = root; database = clientes; password = '';");
public frmCadastro()
{
InitializeComponent();
}
private void frmCadastro_Load(object sender, EventArgs e)
{
}
private void btnCancela_Click(object sender, EventArgs e)
{
Close();
}
private void btnSalvar_Click(object sender, EventArgs e)
{
int cod;
string nome;
string end;
int tel;
cod = Convert.ToInt16(txtCodigo.Text);
nome = txtNome.Text;
end = txtEndereco.Text;
if (txtNome.Text == "")
{
MessageBox.Show("Favor digitar o nome");
}
if (txtCodigo.Text == "")
{
MessageBox.Show("Favor digitar o código");
}
conect.Close();
MySqlCommand insere = new MySqlCommand();
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(@cod + ,'@nome', '@end');";
insere.Parameters.AddWithValue("@cod", cod);
insere.Parameters.AddWithValue("@nome", nome);
insere.Parameters.AddWithValue("@end", end);
conect.Open();
insere.ExecuteNonQuery();// THE ERROR IS HERE!!!!
conect.Close();
MessageBox.Show("Salvo");
}
答案 0 :(得分:7)
您需要打开连接并根据MSDN将其提供给命令:SQLCommand
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection); //<- See here the connection is passes to the command
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
或者您的用法:
conect.Open(); //<- Open Connection first
MySqlCommand insere = new MySqlCommand();
insere.Connection = conect; //<- Set the Commands connection
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(@cod + ,'@nome', '@end');";
insere.Parameters.AddWithValue("@cod", cod);
insere.Parameters.AddWithValue("@nome", nome);
insere.Parameters.AddWithValue("@end", end);
insere.ExecuteNonQuery();
conect.Close();
答案 1 :(得分:1)
此异常通常会导致在连接打开之前调用ExecuteNonQuery()方法的原因
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand command = con.CreateCommand();
command.CommandText="insert into stactoverflowtable (id,name) values('1','adil')";//suppose table name is stackoverflowtalbe
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}