Executenonquery:连接属性尚未初始化

时间:2011-10-30 04:52:59

标签: c# ado.net

此功能将显示“连接未正确初始化”的错误。为什么呢?

public void updateCustomer()
{
     using (SqlCeConnection aConnection = new SqlCeConnection(@"Data Source=|DataDirectory|\Database.sdf"))
     {
            aConnection.Open();
            using (SqlCeCommand aCommand = new SqlCeCommand("UPDATE customer SET credit = @credit WHERE(ID = @ID)"))
            {
                aCommand.Parameters.Add(new SqlCeParameter("credit", SqlDbType.NVarChar, 100)).Value = getRemaining();
                aCommand.Parameters.Add(new SqlCeParameter("ID", SqlDbType.Int, 8)).Value = Convert.ToInt32(textBox2.Text);

                int resultUpdate = aCommand.ExecuteNonQuery();
                if (resultUpdate != -1)
                    label9.Text = "customer updated sussessfully";
                else
                    label9.Text = "some error in updating customer";
                aConnection.Close();
            }
     }
}

2 个答案:

答案 0 :(得分:3)

您需要设置SqlCeCommand

的连接
SqlCeCommand command = new SqlCeCommand(
    queryString, connection);

将连接字符串设置为

@"Data Source=|DataDirectory|\Database.sdf;Persist Security Info=False;"

检查Connection strings for SQL Server Compact Edition以获取更多信息

答案 1 :(得分:-1)

我忘了unhandledexception

所说的这件事

很多时候。每次使用sqlcommand时都需要con作为参数......

否则使用名为Sqldataadapter的更高级实用程序...