Thursday, September 6, 2007

Problem with parameterized Query in asp.net and Microsoft Access

today i face a problem with my asp.net application. the update query i write doesn't update value inside database and there is no error state while running the application. i also try to test run the query inside microsoft access query builder, it works just fine. so after trying and error for a few minute i find a simple solution or simply rules(maybe)

Here the sample code:

dim strQuery as string
dim olecmd as oledbcommand
dim oleparam as oledbparameter

strQuery = "update dsb_mthinp set dsb_mthinp_value=@value where dsb_inpfield_code=@inpcode and dsb_mthinp_month=@month and dsb_mthinp_year=@year"

olecmd = new oledbcommand(strQuery, dbconn)

oleparam = new oledbparameter
oleparam.parametername = "@inpcode"
oleparam.value=getInputcode
olecmd.parameter.add(oleparam)

oleparam = new oledbparameter
oleparam.parametername = "@month"
oleparam.value=getInputcode
olecmd.parameter.add(oleparam)

oleparam = new oledbparameter
oleparam.parametername = "@year"
oleparam.value=getInputcode
olecmd.parameter.add(oleparam)

oleparam = new oledbparameter
oleparam.parametername = "@value"
oleparam.value=getInputcode
olecmd.parameter.add(oleparam)

dbconn.open()
olecmd.executeNonQuery
dbconn.close()

if you can see in the sample code that i marked as bold and italic, i'm writting the parameter value in the wrong order, means i start "@inpcode" as the first parameter rather than "@value". this lead to wrong parameter value during executing the sql statement. means value for:

"@value" = getInpcode
"@inpcode" = getmonth
"@month" = getYear
"@Year" = getValue

basically i really don't understand why this problem happen, it is because i already provide the parameter name, means the value should follow the parameter name. but perhaps it just a rule that i missed read somewhere in .net documentation.

so the solution is simple, put the first parameter "@value" before the "@inpcode" parameter, or in other words follow the order of parameter you write in your sql statement, then your query will run as you wish...

this solution applied to :
asp.net 2.0 and microsoft access 2000 database

that's all... and happy coding

No comments: