Showing posts with label sqlcommand. Show all posts
Showing posts with label sqlcommand. Show all posts

Monday, March 26, 2012

Insert with Parameters (SQL Server)

Hello, this is my code:

SqlCommand cmd =new SqlCommand("INSERT INTO Users (Username,Password) " +"VALUES ('@.username','@.password' ",new SqlConnection(my_ConnectionString)); cmd.Parameters.Add("@.username", SqlDbType.NVarChar, 50).Value = txtUsername.Text;cmd.Parameters.Add("@.password", SqlDbType.NVarChar, 50).Value = txtPassword.Text cmd.Connection.Open();cmd.ExecuteNonQuery();cmd.Connection.Close();

But in the database, the row inserted is exactly this:

"@.username" "@.password"

I mean, the parameters are not inserted :S

Please, tell me the error in the code...
Thank you so much,

Carlos.Placing single quotes around the parameters makes them be treated as literal strings. Remove the single quotes and you should have better luck.|||Thank you, now it works ;)

Carlos.

Friday, March 9, 2012

Insert SQL on Sql Command

i'm using an sql command for insert query

it looks like this

cmd=new sqlcommand("insert into tblname values('" & textbox1.text & "')",cn)
cmd.executereader

the problem is if i type a singlequote or double quote an error is throwing,invalid syntax ...

how can i s'rt out it with out using a sql stored procedure

thanks in advance
PrasantHHi,
try replacing the single quotes present in your input with double single quotes ... example below:

string sqlInput = textbox1.text.Replace("'","''");

In the above code what I have done is that I have replaced all single quotes (') with two single quotes (''). The Sql database will store a single quote when i encounters two single quotes in your query. Hope this solves ur issue.

CreProDes|||you dont have to worry about it if you use parameterized queries..