插入数据库时出现奇怪的 C# 错误
Strange C# error while inserting in database
我的程序中有 2 个表格。我正在使用来自 C#
的 SQL Server Compact 3.5 数据库文件 (.sdf
)
albums_tbl
table 有两列: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 中的确切代码时,当我想插入时出现错误:
您还没有打开连接。
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
希望对您有所帮助。
您还没有打开连接,您只需按照以下步骤操作即可
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();
}
我的程序中有 2 个表格。我正在使用来自 C#
的 SQL Server Compact 3.5 数据库文件 (.sdf
)
albums_tbl
table 有两列: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 中的确切代码时,当我想插入时出现错误:
您还没有打开连接。
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
希望对您有所帮助。
您还没有打开连接,您只需按照以下步骤操作即可
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();
}