使用,
Visual Studio 2012 C# WPF SQL Server Compact 4.0
我的代码在这里。当我提交我的categoryName时,它会显示
“ExecuteNonQuery:Connection属性尚未初始化”
Plz帮助我。我正在尝试将文本框中的数据添加到数据库中。
private void btnCategoryAdd_Click(object sender, RoutedEventArgs e)
{
con.Open();
SqlCeCommand com = new SqlCeCommand("INSERT INTO Category_Master(CategoryName) VALUES(@CategoryName)");
com.Parameters.AddWithValue("@CategoryName", tbCategoryName.Text);
try
{
int affectedRows = com.ExecuteNonQuery();
if (affectedRows > 0)
{
System.Windows.Forms.MessageBox.Show("Insert Success !", System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
tbCategoryName.Text = "";
}
else
{
System.Windows.Forms.MessageBox.Show("Insert Failed !", System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
}
答案 0 :(得分:3)
您错过了将连接实例传递给SqlCeCommand
SqlCeCommand com = new SqlCeCommand("INSERT INTO Category_Master(CategoryName) VALUES(@CategoryName)",con);
答案 1 :(得分:0)
分配连接属性
com.Connection = con