Friday, 15 March 2013

sql - string not accepting " 's " while writing to database -



sql - string not accepting " 's " while writing to database -

hello creating settings page application using mvc4. in settings page:

1.it contains 2 text areas wherein user can type anything.

2.after typing if user clicks submit button, text has written saved in sql database.

3.the main application read info database , display it.

here respective codes:

model:

public string partnerinfo1 { get; set; } public string partnerinfo2 { get; set; }

controller:

[httppost] public actionresult index(adddetailmodel model) { pinfo1 = model.partnerinfo1; pinfo2 = model.partnerinfo2; sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["sample"].connectionstring); con.open(); sqlcommand cmd = new sqlcommand("update dbo.partner_design set partnerinfo1='" + pinfo1 + "',partnerinfo2='" + pinfo2 + "' [partnerid]='cs'", con); cmd.executenonquery(); homecoming redirecttoaction("index"); }

and in view:

@html.textareafor(m => m.partnerinfo1) @html.textareafor(m => m.partnerinfo2)

in database, corresponding table contains 2 columns partnerinfo1,partnerinfo2 , datatype nvarchar(max).

my problem when type apostrophe in text area gives me error.for illustration if type "world's" gives error on clicking submit button.

this error:

incorrect syntax near 's'. unclosed quotation mark after character string ''.

please suggest can avoid this.any help appreciated.

your method expose query sql injection attacks. much improve using parameterised query sort out ' issue well.

string connstring = configurationmanager.connectionstrings["sample"].connectionstring; using (sqlconnection con = new sqlconnection(connstring)) { sqlcommand cmd = new sqlcommand("update dbo.partner_design " + "set partnerinfo1=@pinfo1, " + "partnerinfo2=@pinfo2 " + "where [partnerid]=@partnerid", con); cmd.parameters.addwithvalue("@pinfo1", model.partnerinfo1); cmd.parameters.addwithvalue("@pinfo2", model.partnerinfo2); cmd.parameters.addwithvalue("@partnerid", "cs"); con.open(); cmd.executenonquery(); }

sql asp.net-mvc data-type-conversion

No comments:

Post a Comment