刚开始接触ASP.NET的时候,对类似"select count(*) from Student_tbl where stuID='"+ID+"'"+" and stuName='"+Name+"'"的句子不甚理解,不知道那些引号是怎么回事,今天又好好的看了一下,终于明白了。    例如,我有一个表,存储学生的姓名(nvarchar类型)和学号(nvarchar类型)
假设有一个学生叫 张三  编号是 2002001 当使用下面的语句时,会有一个查询结果CommandText="select count(*) from Student_tbl where stuID='2002001' and stuName='张三'";
这里的双引号中的就是一个字符串,是一个SQL语句,单引号中的就是查询的字段的值(不知道这么说是不是对的,我按自己的理解,不对的请指正)现在,我把这个句子拆开CommandText="select count(*) from Student_tbl where stuID='2002001'
andstuName='张三'"
为什么要这样呢,因为这样有助于理解(请注意哪些单引号)那么,上面的查询语句可以这样写CommandText="select count(*) from Student_tbl where stuID='"+" 2002001"+"'"+" and" +" stuName='"+"张三"+"'"";上面把一个SQL语句,用双引号和+号分成了几段,两个句子是等效的(是不是对引号有一点明白了)。然后(注意了,下面的是重点了)如果我用定义了2个string类型的变量ID,Name,来接收2001001和张三这2个值即ID="2001001",Name="张三"(值可以是从textbox中取得的,或者其他途径)那么,上面的语句就变成了CommandText="select count(*) from Student_tbl where stuID='"+ID+"'"+" and" +" stuName='"+Name+"'"";然后,我们把它连起来CommandText="select count(*) from Student_tbl where stuID='"   +  ID  +   "'"  +   " and"  +   "stuName='"  +  Name  +  "'"  ";(多加了几个空格,这样看的清楚点)再去掉多余的双引号"select count(*) from Student_tbl where stuID='"   +  ID   +   "'" +" and stuName='"  +  Name  +  "'"  ";(把" and"  +   "stuName='" 连在一起)把值赋上去就成了"select count(*) from Student_tbl where stuID='2001001' and stuName='张三'";实际上就是把要作为语句的部分用双引号框起来,包括'也要用双引号框起来然后用+号把双引号框起来的部分连接起来。希望给不太明白的人一点帮助(多想一下)不正确的地方,希望指正。

解决方案 »

  1.   

    简单的说,字符串类型(varchar/nvachar/char/varchar) 常量,需要使用两个 '(单引号)括起来,字符串本身包含 ' ,需要连续两个 ' 转义,即 '' 表示 ' 数字类型,请不要加 ' ,虽然数据库引擎会进行类型转换日期类型的字符文本,请加 '
      

  2.   

    刚开始的时候老在想
    '"   +  ID  +   "'
    是什么意思
    后来,明白,'"   +  ID  +   "'不是一个整体
      

  3.   

    INSERT INTO 
    tbl(UserID, UserName, Description, DateCreated) 
    VALUES(911, 'Jinglecat', 'Leo''s Account Information', '2007-8-18')
      

  4.   

    后来,明白,'" + ID + "'不是一个整体=========为了可读性,你可以考虑如此格式化,string sqlInsert = String.Format("INSERT INTO 
    tbl(UserID, UserName, Description, DateCreated) 
    VALUES({0}, '{1}', '{2}', '{3}')", 
    911, "Jinglecat", ("Leo's Account Information").Replace("'", "''"), "2007-8-18");
      

  5.   

    to 晓风残月'Leo''s Account Information'是不是表示Description的内容是Leo's Account Information