C# 插入到SQL Server CE数据库

C# 插入到SQL Server CE数据库,c#,insert,sql-server-ce,C#,Insert,Sql Server Ce,如何在.sdf数据库的表中插入 我尝试了以下方法: string connection = @"Data Source=|DataDirectory|\InvoiceDatabase.sdf"; SqlCeConnection cn = new SqlCeConnection(connection); try { cn.Open(); } catch (SqlCeException ex) { MessageBox.Show("Connection failed"); M

如何在
.sdf
数据库的表中插入

我尝试了以下方法:

string connection = @"Data Source=|DataDirectory|\InvoiceDatabase.sdf";
SqlCeConnection cn = new SqlCeConnection(connection);

try
{
   cn.Open();
}
catch (SqlCeException ex)
{
    MessageBox.Show("Connection failed");
    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
    Application.ExitThread();
}

string clientName = txt_ClientName.Text;
string address = txt_ClientAddress.Text;
string postcode = txt_postcode.Text;
string telNo = txt_TelNo.Text;

string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)Values(" + clientName + "','" + address + "','" + postcode + "','" + telNo + ")");
SqlCeCommand cmd = new SqlCeCommand(sqlquery, cn);

try {
  int affectedRows = cmd.ExecuteNonQuery();

  if (affectedRows > 0)
  {
     txt_ClientAddress.Text = "";
     txt_ClientName.Text = "";
     txt_postcode.Text = "";
     txt_TelNo.Text = "";
     MessageBox.Show("Client: " + clientName + " added to database. WOoo");
  }
}
catch(Exception){
    MessageBox.Show("Insert Failed.");
} 
但我做什么似乎无关紧要,只是显示“插入失败”


提前感谢。

您忘记了第一个值的开头引号

Values(" + clientName + "','"
改为:

Values('" + clientName + "','"
但这通常是一种构建查询的糟糕方法。改用参数化查询。
见:


将为您提供有关错误的详细信息。

您的SQL语句不正确

string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)Values('" + clientName + "','" + address + "','" + postcode + "','" + telNo + "')");

拿着这个。您忘记了值的开头和结尾的“这是同一个老故事。当您构建一个连接字符串的sql命令时,这些类型的错误都会发生。简单的语法问题并不是最糟糕的。这是最危险的

请以这种方式构建查询

string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)" + 
                   "Values(@client,@address, @postcode, @tel)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, cn);
cmd.Parameters.AddWithValue("@client", clientName);
cmd.Parameters.AddWithValue("@address", address);
cmd.Parameters.AddWithValue("@postcode", postcode);
cmd.Parameters.AddWithValue("@tel", telNo);
cmd.ExecuteNonQuery();
正如其他人已经说过的,您的语法错误是由于省略了最初的单引号引起的。但你可能会有其他错误。例如,一个名为
O'Hara
的客户机呢?。现在,clientname中只有一个引号,这将严重破坏字符串连接。
相反,参数将被准确解析,找到的每个有问题的字符都将得到适当处理(在本例中,将单引号加倍)

要将数据插入Sql,应考虑数据类型。如果插入字符串值(varchar),则必须用单引号将其括起来,如“+full_Name+”,但整数类型不需要这样。范例

string myQuery = "INSERT INTO Persons (phone, fullname) VALUES ("+telNo+",'"+full_Name+"')";

其中,全名是字符串变量,电话号码是唯一的号码。

请捕捉具体的例外情况,并在此处发布消息+1000000,如果我可以的话-非常同意;如果今天仍有人在教学生连接他们的SQL语句,他应该被一根羽毛挠死。@marc_s:我认为勺子更合适。
string myQuery = "INSERT INTO Persons (phone, fullname) VALUES ("+telNo+",'"+full_Name+"')";