来源:作者: 发布时间:2007-12-26 02:08:57


本文假定读者已对数据库连接技术有所了解,因此只讨论有关sql查询命令的语法。
表结构如下(ms access 2000):
表名:usertable
----------------------
字段名 字段类型
----------------------
userid 自动计数(长整型)
username 文本
usersex 文本
createdate 日期/时间(默认值为now())
----------------------
一、用select命令提取记录
1、取得表中任何记录
select命令,语句如下:
"select *from usertable"
2、取得表中userid字段记录
"select userid from usertable"
3、取得表中userid、usersex字段记录
"select userid, usersex from usertable"
4、取得表中usersex值为“男”的记录
"select from usertable where usersex = 男"
5、取得表中username值中包含“张”字的记录
"select from usertable where username like %男%"
6、取得表中任何记录,按createdate字段值降序排列
"select from usertable order by createdate desc"
说明:
1)、以上命令能够组合使用,如,取得表中username中包含“浩”字的,userid的值,并按createdate值的时间降序排列,那么命令如下:
"select userid from usertable where username like %浩% order by createdate desc"
2)、使用中应注意,假如字段类型为文本,则在条件判别时,应在条件字外加上单引号,此规则适用于任何一个sql查询命令。
3)、条件字中的“%”为通配符。
4)、当判别条件多于一条时,应以“and”或“or”连接。
二、用insert into命令插入新记录
1、插入一条新记录
"insert into usertable (username, usersex) values (张浩南, 男)"
说明:
这里需要注意的是,插入的记录的值的类型应符合表中的字段类型,否则会出错。其实使用单引号只是个便捷的方法,但并不规范,因为假如要插入的记录中本身含有单引号,则会出现错误(虽然这种情况并不经常发生,但有可能存在)。所以我们最好使用一个自定义的函数来实现单引号的替换。方法如下
function sqlstr(data)
sqlstr="" & replace(data, "", "") & ""
end function
在命令中则为:
dim name, sex
name="张浩南"
sex="男"
"insert into usertable (username, usersex) values (" & sqlstr(name) & ", " & sqlstr(sex) & ")"
这样则无论值中是否含有单引号或双引号均不会出错。
但请注意,这个规则只适用于类型为文本的字段,假如为其他类型,则一般无需考虑,即不必加任何符号。
三、用update更新记录
1、更新全部记录的全部字段
"update usertable set userid=1, usersex=男, username=徐勇, createdate=" & cdate(createdate)
说明:
式中的值能够用运算表达式,如:userid=userid+1等。
2、更新username字段值为“徐勇”的记录值
"update usertable set userid=1, username=徐? where username=徐勇"
说明:
需要组合条件查询时,方法同select。另外此处也要注意单引号问题。
四、用delete删除记录
1、删除全部记录
"delete from usertable"
2、删除特定条件的记录,如删除userid为“20”的记录
"delete from usertable where userid=20"
3、删除组合条件记录,如删除usersex为“女”,username中包含“张”的记录
"delete from usertable where usersex=女 and username like %张%"
说明:
注意单引号问题。
以上是asp连接数据库技术时使用sql查询语言时的常用命令及其技巧,其实sql命令更有很多,只是并不一定都是常用命令,假如想了解更多,请查阅有关资料。另外,以上内容为本人随手写就,手边并无参考资料,因此如有错误,请多包含,谢谢观赏。
|
还没有关于此文章的相关评论!