执行非查询。连接 属性 尚未初始化

ExecuteNonQuery. connection property has not been initialized

大家好,我在我的代码中遇到了这个错误,但似乎在处理其他新项目时它总是突出显示 ExecuteNonQuery。 我试着用 google 和这个网站搜索解决方案,但是伙计们,我真的不知道为什么它有以下错误。

我也在 mssql express 中使用。

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 System.Data.SqlClient;

namespace AssetInsert
{
    public partial class AssetInsert : Form
    {
        public AssetInsert()
        {
            InitializeComponent();
        }

    private void ICButton_Click(object sender, EventArgs e)
    {
        DBConn.DBOpen();
        lbConnTest.Text = "OK";
        DBConn.DBClose();
    }
    private void ISaveButton_Click(object sender, EventArgs e)
    {
        string sql = (@"INSERT INTO dbo.HWTable(Brand, CPU, RAM, HSerial, Model, ACode, PYear, UName, Position, Depart) VALUES('" + BrandCBox.Text + "', '" + CPUTBox.Text + "', '" + RAMTBox.Text + "', '" + HSerialTBox.Text + "', '" + ModelTBox.Text + "', '" + ACodeTBox.Text + "', '" + PYearPicker.Text + "', '" + UNameTBox.Text + "', '" + PositionCBox.Text + "', '" + DepartCBox.Text + "');");
        SqlCommand cmd = new SqlCommand(sql);
        DBConn.DBOpen();
        cmd.Parameters.AddWithValue("@Brand", BrandCBox.Text);
        cmd.Parameters.AddWithValue("@CPU", CPUTBox.Text);
        cmd.Parameters.AddWithValue("@RAM", RAMTBox.Text);
        cmd.Parameters.AddWithValue("@HSerial", HSerialTBox.Text);
        cmd.Parameters.AddWithValue("@Model", ModelTBox.Text);
        cmd.Parameters.AddWithValue("@ACode", ACodeTBox.Text);
        cmd.Parameters.AddWithValue("@PYear", PYearPicker.Text);
        cmd.Parameters.AddWithValue("@UName", UNameTBox.Text);
        cmd.Parameters.AddWithValue("@Position", PositionCBox.Text);
        cmd.Parameters.AddWithValue("@Depart", DepartCBox.Text);
        cmd.ExecuteNonQuery(); //<--error here
        DBConn.DBClose();      
    }

    public class DBConn
    {
        public static void DBOpen()
        {
            string source = @"Data Source = 10.201.0.17; Initial Catalog = ITinven; USER ID = sa; PASSWORD = jc9989;";
            SqlConnection conn;
            conn = new SqlConnection(source);
            conn.Open();
        }

        public static void DBClose()
        {
            string source = @"Data Source = 10.201.0.17; Initial Catalog = ITinven; USER ID = sa; PASSWORD = jc9989;";
            SqlConnection conn;
            conn = new SqlConnection(source);
            conn.Close();
        }
    } 

}

错误信息明确;

connection property has not been initialized

连接你的 SqlComamndSqlConnection 赞;

SqlCommand cmd = new SqlCommand(sql, conn);

奇怪的是,您使用字符串连接添加插入值,但您也尝试将它们添加为参数。阅读:Give me parameterized SQL, or give me death。而且您不需要像这样的 DBOpenDBClose 方法。

作为最佳实践,请改用 using statement to dispose your SqlComamnd and SqlConnection instead of calling .Close() method manually in a different method, and stop using AddWithValue method. It may generate unexpected results. Use .Add() method 或重载。

阅读:Can we stop using AddWithValue() already?

using(SqlConnection conn = new SqlConnection(source))
using(SqlCommand cmd = conn.CreateCommand())
{
   // Set your CommandText property with parameterized way.
   // Add your parameters with .Add() method
   // Open your connection
   // Execute your query.
}

当您在代码中收到任何错误消息或异常时,请仔细阅读。再来一次,再再来一次。这让 更容易 解决您的问题。

(1) 正确的参数传递方式

(2) 始终使用 try-catch 块

(3) 使用 sql 命令文本和 sql 连接初始化 Sqlcommand 的正确方法。

// see how parameters are used

SqlCommand sqlcommand0;

using (SqlConnection conn = new SqlConnection(con_str))

{

    conn.Open();

    string sql = "INSERT INTO dbo.HWTable(Brand, CPU, RAM, HSerial, Model, ACode, PYear, UName, Position, Depart) VALUES(@Brand, @CPU, @RAM, @HSerial, @Model, @ACode, @PYear, @UName, @Position, @Depart)";       // (1)

    try                                                // (2)

    {

        using (sqlcommand0 = new SqlCommand(commandtext, conn)) // (3)

        {

            sqlcommand0.Parameters.Add(new SqlParameter("@Brand", Brand.Text));

            sqlcommand0.Parameters.Add(new SqlParameter("@CPU", CPU.Text));

            ....

            sqlcommand0.ExecuteNonQuery();

        }

    }

    catch

    {

        Console.WriteLine("Count not insert data into table.");

    }

}