字符串加入''单引号:代码分析器遇到一个单引号,就认为字符串文字开始,然后遇到下一个单引号的时候,它不会立即认为字符串结束,而是再读取下一个字符,如果还是单引号,则把这两个单引号解释为字符串中的一个单引号,并且继续分析后面的字符,直到遇到一个单引号后不是单引号,就认为这个字符串结束。
例一:
string.Format("delete from [escale_std] where identifier= "+"'dataGridView1.Rows[1].Cells[0].Value.ToString().Trim()'")
返回的结果
delete from [escale_std] where identifier= 'dataGridView1.Rows[1].Cells[0].Value.ToString().Trim()' //没有变换数值,失败
例二:
string.Format("delete from [escale_std] where identifier= "+dataGridView1.Rows[1].Cells[0].Value.ToString().Trim())
返回的结果
delete from [escale_std] where identifier= F0779 //F0779无单引号,失败
例三:
string.Format("delete from [escale_std] where identifier= "+"'"+dataGridView1.Rows[1].Cells[0].Value.ToString().Trim()+"'")
返回的结果
delete from [escale_std] where identifier= 'F0779' //有单引号,符合预期,其中+"'" 是为了增加前后单引号'
例四:
string.Format("delete from [escale_std] where identifier= '"+dataGridView1.Rows[1].Cells[0].Value.ToString().Trim()+"'")
返回的结果
delete from [escale_std] where identifier= 'F0779' //有单引号,符合预期
例五:
string.Format("delete from [escale_std] where identifier= '{0}'",dataGridView1.Rows[1].Cells[0].Value.ToString().Trim())
返回的结果
delete from [escale_std] where identifier= 'F0779' //符合预期,有更好的可读性
c#中的单引号
最新推荐文章于 2021-11-25 10:28:49 发布