【发布时间】:2014-06-25 03:24:34
【问题描述】:
我正在尝试将值添加到数据库中,但每次我尝试添加一些内容时,我都会在 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");
}
【问题讨论】:
-
您需要打开连接并将其提供给命令。
-
insere.Connection = conect;在你执行之前
-
感谢@dbugger 和杰里米汤普森!!!!非常感谢!!!!!!
-
@Bordotti 你应该从你的代码中删除注释,任何英语用户都不理解。
-
对不起@Dhwani 我只是用英文评论错误在哪里,所有其他 cmets 都没有谈论错误..
标签: c# database executenonquery