C# - 更新语句到SQL Server的问题 [英] C# - Issue with update statements to SQL Server

查看:83
本文介绍了C# - 更新语句到SQL Server的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我正在使用C#测试更新语句到SQL的过程。

我发现更新语句通过,但数据库没有更新。



我错过了一个提交(或者类似的东西)?



这是我到目前为止所拥有的:

Hi everyone,

I am in the process of testing update statements to SQL using C#.
I am finding that the update statements pass, but the db doesn''t get updated.

Am I missing a commit (or something similar) ?

Here is what I have so far:

try
{
      SqlCeCommand updateKeyCommand = new SqlCeCommand("UPDATE testtable SET Test_Col_1 = '" + resultingString + "' WHERE Test_Col_1 = '" + replaceKeyCommand_dr.GetString(0) + "'", conn);
      
      updateKeyCommand.CommandType = CommandType.Text;
      updateKeyCommand.ExecuteNonQuery();

      MessageBox.Show("Successful...");
}
catch (Exception ex)
{
      MessageBox.Show(ex.Message);
}





没有错误被抛出,但数据库没有根据我的内容进行更新看到。

任何人都可以了解我错过的内容吗?



No errors are being thrown, but the db doesn''t get updated according to what I''m seeing.
Can anyone shed some light as to what I''m missing?

推荐答案

(1)确保更新现有表格/ column / row

(2)确保您使用的命令不包含字符(''),因为sql将无法将语法识别为命令。

例如:

(1) Make sure that you update an existing table/column/row
(2) Make sure that the command that you use does not contain the character ('') because sql will not be able to recognize the syntax as a command.
For example :
"UPDATE testtable SET Test_Col_1 = 'someString' WHERE Test_Col_1 = 'someSt'ring'





所以你能做的就是写一个方法,以确保('')永远不会独立



这应该工作:





So what you could do in this is to write a method to make sure that ('') will never be stand alone

This should work :

private string generateQueryableString(string s)
{
	if (s == null){
	     return "";
         }

	 StringBuilder stringBuilder = new StringBuilder();

         for (int i = 0; i < s.Length; i++){
               if (s[i] == '\''){
                    if (!((((i - 1) >= 0) && s[i - 1] == s[i]) ^ 
                        (((i + 1) < s.Length) && s[i + 1] == s[i]))){
				stringBuilder.Append(s[i]);
			 }
		}
			  stringBuilder.Append(s[i]);
	    }

          return stringBuilder.ToString();

}







备注:对你来说可能有好处使用String.format()来组织命令




Side Note: It might be good for you to use, String.format() to organize your command


这篇关于C# - 更新语句到SQL Server的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆