Saturday, 15 September 2012

c# - Insert data into database with one integer value -



c# - Insert data into database with one integer value -

i'm tyring insert info table within database 1 value needs integer. how prepare this? is code far: have 3 textboxes values can set , button send it.

private void button1_click(object sender, eventargs e) { //maak inert query string sqlins = @"insert pizza (soort, beschrijving, prijs) values ('" + textboxsoort.text.trim() + "','" + textboxbescrhijving.text.trim() + "', '" + tetboxprijs +"') "; //maak commando object oledbcommand command = new oledbcommand(sqlins, connectie); seek { //open de connectie connectie.open(); //voer commando uit command.executereader(); connectie.close(); //opnieuw vullen datagridvieuw vullendgv(); } grab (oledbexception ex) { messagebox.show(ex.message + ex.stacktrace, "exception details"); } { //sluiten van de connectie connectie.close(); textboxsoort.clear(); textboxbescrhijving.clear(); tetboxprijs.clear(); } }

you have several issues regarding code:

use parameterized queries prevent sql injection. inline queries devil!

validate input before placing in query. if value of textbox should numeric, validate or create textbox take numeric input. accomplish create method checks if input numeric (regex or custom code) , if want numeric-only tetxbox read this article.

an illustration when using regular look check if input numeric:

string numericpattern = "^[0-9]+$"; string input = "1zd23"; bool result1 = regex.ismatch(value, numericpattern); //false string input = "456"; bool result2 = regex.ismatch(value, numericpattern); //true

and in method:

public bool isnumeric(string input) { homecoming regex.ismatch(input, "^[0-9]+$"); } //usage: bool result = isnumeric("qsd4156"); //false

in query you're adding textbox-object tetboxprijs query, not value. leave out single quotes, otherwise not treated numeric value in sql. utilize code instead

tetboxprijs.text

but must numeric should be:

convert.toint32(tetboxprijs.text)

of course of study without validation of input. validation can done provided method using regular expression:

if(isnumeric(tetboxprijs.text)) { int prijs = convert.toint32(tetboxprijs.text); //use 'prijs' in query }

update:

even more simple utilize int32.tryparse method commented garethd:

int numericvalue; if(int32.tryparse(tetboxprijs.text, out numericvalue)) { //valid, utilize in query } else { //not numeric, inform user }

c# sql

No comments:

Post a Comment