1

I have this code and when I run it gives this error ExecuteNonQuery: Connection property has not been initialized. And I have sql database. its name is Cost. I have this code and when I run it gives this error ExecuteNonQuery: Connection property has not been initialized. And I have sql database. its name is Cost. My code is:

    namespace Accountingss
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public SqlConnection conn;

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Connect(string cmdtxt, Hashtable parameters)
        {
            conn = new SqlConnection();
            string connString = @"Data      Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Cost.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            conn.ConnectionString = connString;
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = cmdtxt;
            cmd.Parameters.Clear();
            var ieParams = parameters.GetEnumerator();
            while (ieParams.MoveNext())
            {
                cmd.Parameters.AddWithValue(ieParams.Key.ToString(), ieParams.Value.ToString());
                //cmd.Parameters.Add(new SqlParameter(ieParams.Key.ToString(), ieParams.Value.ToString()));
            }

            conn.Open();
            cmd.ExecuteNonQuery();

            //SqlDataAdapter costdataAdpater = new SqlDataAdapter();
            //DataTable costdataTable = new DataTable(); 
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string insert = "INSERT INTO Cost (Type, Amount) VALUES (@type,         @amount)";// +type.Text + ',' + a.Text + ")";
            var addpTA = new Hashtable();
            addpTA.Add("@type", txtType.Text);
            addpTA.Add("@amount", txtAmount.Text);
            Connect(insert, addpTA);
        }
    }
}
4

4 回答 4

3

您必须为 sql 命令分配连接,如下所示。看来你忘了这样做了。

cmd.Connection = conn;
于 2012-07-24T09:49:36.730 回答
3

You didn't connected the command to the connection.

cmd.Connection = conn;

And after executing the command you should close it.

conn.Close();
于 2012-07-24T09:57:09.620 回答
1

只需在执行之前将 SqlConnection 连接到您的 SqlCommand

cmd.Connection = conn;

Connection 对象是将我们的命令传递给底层数据库引擎的工具。
如果我们想访问数据库,我们需要将它与我们的命令联系起来。

一个很好的快捷方式是使用此方法直接从连接创建命令

   SqlCommand cmd = conn.CreateCommand();
于 2012-07-24T09:47:57.200 回答
1

您应该将连接传递给命令

SqlCommand cmd = new SqlCommand(conn);

或者

cmd.Connection = conn;
于 2012-07-24T09:48:13.213 回答