2013-03-27 137 views
-2

如何在.sdf数据库中插入表格?插入SQL Server CE数据库

我已经试过如下:

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."); 
} 

但它似乎并不无论我做什么,它只是显示“插入失败”。

在此先感谢。

+1

请抓住混凝土异常并在这里发布消息 – Tomtom 2013-03-27 13:33:53

回答

1

您的SQL语句不正确。

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

拿着这个。你忘了'在开始和结束的价值

2

这是老一套的故事。当你建立一个sql命令连接字符串这些种类的错误丰富。简单的语法问题并不是最糟糕的。 Sql Injection是最危险的。

请构建查询这样

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的客户呢?现在你在客户端里面有一个单引号,这会对你的字符串连接造成严重影响。 代替参数将被准确地解析,发现每存在问题的字符将被适当地处理(在这种情况下,单引号加倍)

+2

+1000000如果我可以 - 不能同意更多;如果今天有人仍在教学生将他们的SQL语句连接在一起 - 他应该用羽毛搔痒死去...... – 2013-03-27 13:44:52

+1

@marc_s:我认为勺子会更合适。 – NotMe 2013-03-27 16:19:23

0

要插入数据到SQL,数据类型应该被考虑。如果你插入一个字符串值(varchar),你必须用单引号括起来,比如''+ full_Name +'',但是整数类型不需要这个。例如

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

其中全名是字符串变量和电话号码,只有号码。