Showing posts with label cmd. Show all posts
Showing posts with label cmd. 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.

Wednesday, March 7, 2012

Insert Query has Conflict with Foreign Key

there have a exception when I trying to run a insert query

the exception is occur on cmd.ExecuteReder(); and shows
Insert Query conflict with Foreign key..

why? and how to resolve it?


thank you

You need to look up foreign keys in books online, but basically it has to do with putting invalid data into a column that references the data in the primary (or unique) key of another table. As an example:

use tempdb
go
create table parent
(
parentId int primary key
)
go
create table child
(
childId int primary key,
parentId int foreign key references parent(parentId)
)
go
insert into child
values (1,1)
go
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__child__parentId__0CBAE877". The conflict occurred in database "tempdb", table "dbo.parent", column 'parentId'.
The statement has been terminated.
go
insert into parent
values (1)
go
insert into child
values (1,1)