Sql数据库不会更新

时间:2015-03-04 10:06:41

标签: c# sql winforms

我在SQL Server中更新SQL数据库时遇到问题。我有以下代码:

 String connectionQuery = conString.Text;
                SqlConnection connection = new SqlConnection(connectionQuery);

 DataTable datTable = new DataTable();

 String costsUnconverted = costs.Text;
                String costsConverted = null;

                if(costsUnconverted.Contains(","))
                {
                    costsConverted = costsUnconverted.Replace(",",".");
                }

                SqlDataAdapter sqlDatAdapter = new SqlDataAdapter(@"INSERT INTO [" + tableName.Text + "] (["+cusIDColumn.Text+"],["+cusNameColumn.Text+"],["+costsColumn.Text+"],) VALUES('"+cusId.Text+"','"+cusName.Text+"','"+costsConverted+"')", connection);
                //sqlDatAdapter.Fill(datTable);

所以我转换成本值,如果有","到"。"。我不知道UPDATE声明有什么问题。不知怎的,他什么也没做。我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

您必须使用SqlCommandExecuteNonQuery将数据插入表格。请参阅this

答案 1 :(得分:0)

使用 SqlCommand Class 。您应该使用Using块来确保正确处理连接。最重要的是使用参数化查询来避免Sql注入。所以你想要像

这样的东西
using (SqlConnection con = new SqlConnection("YourConnectionString")) 
{
 using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTable(FirstColumn, SecondColumn) VALUES(@FirstValue, @SecondValue)", con))
  {
     cmd.Parameters.Add("@FirstValue", SqlDbType.VarChar, 20).Value = "SomeValue";
     cmd.Parameters.Add("@SecondValue", SqlDbType.VarChar, 20).Value = "SomeValue";
      ...
     con.Open();
     cmd.ExecuteNonQuery();
  }
} //Connection will get disposed here