【问题标题】:C# ExecuteNonQuery "Connection must be valid and open."C# ExecuteNonQuery “连接必须有效且打开。”
【发布时间】: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


【解决方案1】:

您需要打开连接并将其提供给 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();

【讨论】:

  • 是的@jeremy 我写了这行代码,一切都很完美!!谢谢!
【解决方案2】:

此异常通常会导致在打开连接之前调用 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;

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多