我的程序中有2个表单。我正在使用C#
中的SQL Server Compact 3.5数据库文件(.sdf
)
albums_tbl
表有两列:id
,name
使用此代码时,在表单1中:
private void button1_Click(object sender, EventArgs e)
{
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (@album_name) ", cn);
cm.Parameters.AddWithValue("@album_name", textBox1.Text);
int affectedrows = cm.ExecuteNonQuery();
if (affectedrows > 0)
{
MessageBox.Show("insert shod !");
}
}
该程序插入良好,但当我使用表单2中的确切代码时,它会在我想插入时出错:
答案 0 :(得分:1)
您尚未打开连接。
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Customers ([Customer ID], [Company Name]) Values('NWIND', 'Northwind Traders')";
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
参考:https://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
希望这有帮助。
答案 1 :(得分:0)
您尚未打开连接,只需执行以下操作
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection con=new SqlCnConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (@album_name) ", cn);
cm.Parameters.Add(new SqlCeParameter(@album_name, textBox1.Text));
con.Open();
cm.ExecuteNonQuery();
}