Error when trying to insert a variable from C# into MySQL -
this question has answer here:
- parameterized query mysql c# 6 answers
here code i'm using insert values database.
public void callsql(string partnumber, string total, string numofpacks, string dunsnumber, string serialnumber, string lanenumber) { mysqlconnection myconnection = new mysqlconnection("server=localhost;database=testing;uid=root;password=********;"); try { myconnection.open(); console.writeline(lanenumber); mysqlcommand mycommand = new mysqlcommand("insert test (part_number, total, number_of_packs, dunsnumber, serialnumber, truck_number) values (" + partnumber +","+total+","+numofpacks+","+dunsnumber+","+serialnumber+","+lanenumber+")", myconnection); mycommand.executenonquery(); console.write("done"); myconnection.close(); } catch (exception e) { console.writeline(e.tostring()); } }
its weird happens. problem getting lanenumber variable. string read console.
console.writeline("please enter date , lane number so: ddmmyylanenumber."); string lanenum = console.readline();
however gets inputted database when numbers. moment there character in there, not able input database. works when manually change variable string, not when use variable characters inside. error this:
"mysql.data.mysqlclient.mysqlexectipn (0x8004005): unknown column 'whatever_i_entered_into_console' in 'field list'
the line compiler complains mycommand.exectuenonquery();
line.
hope enough information. in advance.
edit truck_number varchar.
from comments mentioned truck_number
column varchar
type.
problem : not enclosing string value lane_number
within single quotes.
solution : need enclose string values varchar
types within single quotes send them :
try this: (i don't suggest this)
mysqlcommand mycommand = new mysqlcommand("insert test (part_number, total, number_of_packs, dunsnumber, serialnumber, truck_number) values (" + partnumber +","+total+","+numofpacks+","+dunsnumber+","+serialnumber+",'"+lanenumber+"')", myconnection);
suggestion : insert into
statement open sql injection attacks
. suggest use parameterised queries
avoid them.
when use parameterised queries
respective types willbe sent properly,so don't need use single quotes while sending string values.
using parameterised queries :
mysqlcommand mycommand = new mysqlcommand("insert test (part_number, total, number_of_packs, dunsnumber, serialnumber, truck_number) values (@part_number,@total,@number_of_packs,@dunsnumber,@serialnumber,@truck_number)", myconnection); mycommand.parameters.addwithvalue("@part_number",partnumber); mycommand.parameters.addwithvalue("@total",total); mycommand.parameters.addwithvalue("@number_of_packs",numofpacks); mycommand.parameters.addwithvalue("@dunsnumber",dunsnumber); mycommand.parameters.addwithvalue("@serialnumber",serialnumber); mycommand.parameters.addwithvalue("@truck_number",lanenumber); mycommand.executenonquery();
Comments
Post a Comment