SQL查询未向数据库插入正确的值

时间:2013-02-08 20:31:52

标签: sql sql-server database

这是SQL语句:

SQL = "INSERT INTO MYIMAGES(image_blob, filename, description, filesize, accountnum, rmanum, billol, copiedfilename) VALUES(?, '"
SQL = SQL & File.Filename & "', '"
SQL = SQL & Replace(Upload.Form("DESCR"), "'", "''") & "', '"
SQL = SQL & File.Size & "', '"
SQL = SQL & Replace(Upload.Form("accountnum"), "'", "''") & "', '"
SQL = SQL & Replace(Upload.Form("rmanum"), "'", "''") & "', '"
SQL = SQL & Replace(Upload.Form("billol"), "'", "''") & "', "
SQL = SQL & Replace(Upload.Form("accountnum"), "'", "''") & "-" & Replace(Upload.Form("rmanum"), "'", "''") & ")"

accountnum = 3456345 rmanum = 345234

输入的数据库中的值3111111我想要的是3456345-345234

列的数据类型是varchar(255) - 我做错了什么?

2 个答案:

答案 0 :(得分:3)

如果使用sql参数,可以避免REPLACE以及任何sql注入

例如:

将sql语句更改为

INSERT INTO MYIMAGES(image_blob, filename, description, filesize, 
   accountnum, rmanum, billol, copiedfilename) 
VALUES(@p1, @p2, @p3,@p4,@p5, @p6, @p7,@p8)

然后做

cmd.Parameters.AddWithValue("@p2",File.Filename)
cmd.Parameters.AddWithValue("@p3",Upload.Form("DESCR"))

...

//this will insert correct data
cmd.Parameters.AddWithValue("@p8",Upload.Form("accountnum") & "-" & 
                                  Upload.Form("rmanum"))

根据OP评论更新: 对于ASP试试这个

dim cmd, rs, param1, param2, param3, param4, param5,param6, param7, param8
set cmd = server.CreateObject("adodb.command")
strCmd = "INSERT INTO MYIMAGES(image_blob, filename, description, 
            filesize, accountnum, rmanum, billol, copiedfilename)
            VALUES(?,?,?,?,?,?,?,?)"
Set cmd.ActiveConnection = objConn
cmd.CommandText = strCmd
cmd.CommandType = adCmdText
Set param1 = cmd.CreateParameter ("image_blob", adWChar, adParamInput, 50)
param1.value = image_blob
cmd.Parameters.Append param1
....
Set param8 = cmd.CreateParameter ("copiedfilename", adWChar, adParamInput, 50)
param8.value = Upload.Form("accountnum") & "-" & Upload.Form("rmanum")
cmd.Parameters.Append param8
Set rs = cmd.Execute()

答案 1 :(得分:0)

试试这个:

SQL = "INSERT INTO MYIMAGES(image_blob, filename, description, filesize, accountnum, rmanum, billol, copiedfilename) VALUES(?, '"
SQL = SQL & File.Filename & "', '"
SQL = SQL & Replace(Upload.Form("DESCR"), "'", "''") & "', '"
SQL = SQL & File.Size & "', '"
SQL = SQL & Replace(Upload.Form("accountnum"), "'", "''") & "', '"
SQL = SQL & Replace(Upload.Form("rmanum"), "'", "''") & "', '"
SQL = SQL & Replace(Upload.Form("billol"), "'", "''") & "', '"
SQL = SQL & Replace(Upload.Form("accountnum"), "'", "''") & "-" & Replace(Upload.Form("rmanum"), "'", "''") & "')"

我刚刚把'放到最后一个值的开头和结尾,这样它就不会被解释为数学表达式

是:

3456345-345234 = 3111111