什么时候用撇号将SQL字段括起来? [英] When to surround SQL fields with apostrophes?

查看:78
本文介绍了什么时候用撇号将SQL字段括起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当我在数据库中往返INSERTSELECT的值时,必须用单引号将字段引起来,就像这样:

I notice that when I INSERT and SELECT values to and from a database I have to surround the fields with single quotes, like so:

mysql_query("INSERT INTO employees (name, age) VALUES ('$name', '$age')");

但是,如果我要更新年龄,则不会使用单引号:

However, if I were to update the age, I would not use single quotes:

mysql_query("UPDATE employees SET age = age + 1 WHERE name = '$name'");

此外,似乎在将日期添加到SQL数据库时,也不必用单引号引起来:

Also, it seems when adding the date to a SQL database I do not have to surround it with single quotes either:

mysql_query("INSERT INTO employees (name, date) VALUES ('$name', NOW())");

另外,当使用像CONCAT这样的运算符时,似乎也没有必要:

Also, when using operators like CONCAT it seems not to be necessary either:

mysql_query("UPDATE employees SET name=CONCAT(name,$lastName) WHERE id='$id'");

也许我的编码不佳,但是我似乎想起了在插入和选择该字段时是否没有用单引号引起来的操作.

Perhaps I am just coding poorly but I seem to recall if I did not surround a field with single quotes when inserting and selecting it the operation failed.

推荐答案

当字段数据类型为 string 时,例如,textcharvarchar等或 日期 类型,例如datetimedatetime.

You need to surround the values with quotes when field data type is of string eg text, char, varchar, etc or date types such as date, time, datetime.

对于 数字 类型(例如intbigintdecimal等)或SQL函数(例如now()current_date),您不需要不需要引号.

For numerical types such as int, bigint, decimal, etc or SQL functions such as now(), current_date, you don't need quotes.

这篇关于什么时候用撇号将SQL字段括起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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