任意多字段的INSERT
你遇到过一口气向一个表写N个字段数据的时候吗?(N>30)
是否觉得写一个insert语句都痛苦死了。
1、是否少写了什么字段、
2、是否已经接受了request的值、
3、是否将字段名和 values1,1对齐。
这一些的问题常常困扰着我们
比如 你有一个文件类似于:
------------------------------------
forms.asp
<form method = post action = f2.asp>
<input type = text name = f1><br>
<input type = text name = f2><br>
<input type = text name = f3><br>
<input type = text name = f4><br>
<input type = text name = f5><br>
<input type = text name = f6><br>
<input type = text name = f7><br>
<input type = text name = f8><br>
<input type = text name = f9><br>
<input type = text name = f10><br>
<input type = text name = f11><br>
<input type = text name = f12><br>
<input type = text name = f13><br>
<input type = text name = f14><br>
<input type = text name = f15><br>
<input type = text name = f16><br>
<input type = text name = f17><br>
<input type = text name = f18><br>
<input type = text name = f19><br>
<input type = text name = f20><br>
<input type = text name = f21><br>
<input type = text name = f22><br>
<input type = text name = f23><br>
<input type = text name = f24><br>
<input type = text name = f25><br>
<input type = text name = f26><br>
<input type = text name = f27><br>
<input type = text name = f28><br>
<input type = text name = f29><br>
<input type=submit value = "ok">
</form>
------------------------------------------
用户提交后 我要生成一个:
insert into people(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,f25,f26,f27,f28,f29,people_signaday) values('a','b','c',1,2,3,4,'e','f','g','h',5,6,7,8,9,10,'i','j','k','l','m','n',11,12,13,14,15,16,'2005-9-2')
如果手动写这样一个sql 好痛苦啊。
但是我却很轻松的完成了它。
为什么:
看看我的
----------------------------------------
f2.asp
<%
on error resume next
sql = "insert into people"
namef = "("
valuef = "("
for i= 1 to request.Form.Count
if request.Form(request.Form.Key(i))<>"" then
namef = namef&request.Form.Key(i)&","
end if
if IsNumeric(request.Form(request.Form.Key(i))) = true and len(request.Form(request.Form.Key(i)))<6 then
if request.Form(request.Form.Key(i))<>"" then
valuef = valuef&request.Form(request.Form.Key(i))&","
end if
else
if request.Form(request.Form.Key(i))<>"" then
valuef = valuef&"'"&request.Form(request.Form.Key(i))&"',"
end if
end if
next
namef = namef&"people_signaday)"
valuef = valuef&"'"&date()&"')"
sql = sql&namef&" values"&valuef
response.write sql
response.write err.description
%>
问题解决了。
世界安静了。
a〉缺点:
1、你的表单名必须和你的数据表字段名一致(如果更只能我应该做成配置匹配,但是我的项目用这个足够了);
2、我把数字并且长度小于6的看作数字(这个可以你自己来定);
3、这个代码只能用于asp :) 其他的语言/工具 是一样。
b〉优点:
1、对于前面的f1.asp是透明的,不管f1内有多少个input 或者 select 都通用;
2、我也不管你的input或者select是否有值,他会职能的判断;
3、不用你辛苦的一会的看数据、一会的看那个f1.asp文件
4、代码复杂度降低了,不需要写 很多繁琐的 request.form("")
5、出错的几率降低。
关键你是是否想到了。
如果你有闲心可以把它写成一个方法随时调用。
博客围绕任意多字段的INSERT操作展开,指出手动编写多字段insert语句易出现少写字段、值与字段名未对齐等问题。介绍了通过ASP代码自动生成insert语句的方法,分析了该方法的优缺点,优点是通用性强、能智能判断等,缺点是有一定使用限制。

793

被折叠的 条评论
为什么被折叠?



