关于sql:强势推荐SQL-语句单引号双引号的用法

6次阅读

共计 2265 个字符,预计需要花费 6 分钟才能阅读完成。

作者:peterYong
原文:https://www.cnblogs.com/peter…

对于 Insert 字符串,在 (单引号, 双引号) 这个方面产生了问题,其实次要是因为数据类型和变量在作怪。上面咱们就别离讲述,尽管说的是 Insert 语句,然而 Select、Update、Delete 语句都是一样的。

如果有下述表格:

mytabe
字段 1    username     字符串型(姓名)字段 2    age          数字型(年龄)字段 3    birthday      日期型(生日)字段 4    marry        布尔型(是否结婚,结婚为 True,未结婚为 False)字段 5    leixing       字符串型(类型)

插入字符串型

如果要插入一个名为张红的人,因为是字符串,所以 Insert 语句中名字两边要加单撇号,数值型能够不加单引号

如:

strsql=“Insert into mytable(username) values(‘张红 ')”

如果当初姓名是一个变量 thename,则写成

strsql=”Insert into mytable(username) values(‘”& thename &“')”

阐明:& 改为 + 号也能够吧,字符串连贯

这里

Insert into mytable(username) values(‘是张红后面的局部,thename 是字符串变量,')

是张红前面的局部。

将 thename 变量替换成张红,再用 & 将三段连接起来,就变成了

 strsql=“Insert into mytable(username) values(‘张红 ')”

如果要插入两个字段,如姓名为“张红”,类型为“学生”

strsql=“Insert into mytable(username,leixing) values(‘张红 ',' 学生 ')”

如果当初姓名是一个变量 thename,类型也是一个变量 thetype,

则写成:

strsql=”Insert into mytable(username,leixing) values(‘”& thename &“','”& thetype &“')”

和第一个例子一样,将 thename 和 thetype 替换后,再用连接符,就连接成和下面一样的字符串了。

插入数字型

如果插入一个年龄为 12 的记录,要留神数字不必加单撇号

strsql=“Insert into mytable(age) values(12)”

如果当初年龄是一个变量 theage,则为:

strsql=“Insert into mytable(age) values(“& theage &“)”

这里

Insert into mytable(age) values

(是 12 后面的局部,theage 是年龄变量,)是 12 前面局部。

将 theage 替换,再用 & 连接符将三局部连接起来,就变为了和下面一样的字符。

插入日期型

日期型和字符串型相似,然而要将单撇号替换为 #号。(不过,access 数据库中用单撇号也能够)

strsql=“Insert into mytable(birthday) values(#1980-10-1#)”

如果换成日期变量 thedate

strsql=“Insert into mytable(birthday) values(#”& thedate &“#)”

插入布尔型

布尔型和数字型相似:只不过只有两个值 True 和 False,

如:

strsql=“Insert into mytable(marry) values(True)”

如果换成布尔变量 themarry

strsql=“Insert into mytable(birthday) values(”& themarry&“)”

综合示

插入一个姓名为张红,年龄为 12 的记录

strsql=“Insert into mytable(username,age) values(‘张红 ’,12)”

认真留神上式:因为姓名是字符串,所以张红两边加了单撇号;年龄是数字,所以没有加单撇号。

如果换成字符串变量 thename 和数字变量 theage,则变为:

strsql=“Insert into mytable(username,age) values(‘”& thename &“’,”& theage &“)”

留神上式,总之,替换变量,再连贯后要实现和上边一样的字符串。

小窍门

要把上面的语句题换成变量的写法:

strsql=“Insert into mytable(username) values(‘张红 ')”

第一步:先把张红抹去,在原地位 加 两个引号

strsql=“Insert into mytable(username) values(‘”“')”

第二步:在两头增加两个连接符 &

strsql=“Insert into mytable(username) values(‘”& &“')”

第三步:把变量写在两个连接符之间

strsql=“Insert into mytable(username) values(‘”& thename &“')”-

咱们在写 SQL 查问的时候还是不厌其烦的加上单引号吧,仿佛那没有害处。因为对于主键为字符串类型的查问语句,加不加单引号的性能是相差百倍一上的。

如有谬误,欢送斧正,如有帮忙,欢送点赞并转发反对。

更多技术干货分享,敬请关注民工哥集体微信公众号:民工哥技术之路

正文完
 0