I have 2 tables:
RESERVATION
ID, DATE, TIME, TABLE
CLIENT
ID_CLIENT, FNAME, LNAME, EMAIL, PHONE, FK_RESERVATION
I have working INSERT statement for Reservation Table-
string insertSql = "INSERT INTO Rezervacija (date,time,table) VALUES (#date,#time,#table);
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
But the problem comes with INSERT INTO Client Table Foreign Key.
Can anyone help me how to insert data into two related tables.
You'll need to modify your query to get the ID of the row that you just inserted.
string insertSql = "INSERT INTO Rezervacija (date,time,table) OUTPUT INSERTED.Id VALUES (#date,#time,#table);"
SqlCommand cmd = new SqlCommand(insertSql, con);
cmd.Parameters.AddWithValue("#date", txtDate.Text);
cmd.Parameters.AddWithValue("#time", ddlTime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#table", ddlTable.SelectedItem.Text);
var **reservationId** = (int)cmd.ExecuteScalar()
string insertSql2 = "INSERT INTO CLIENT (ID_CLIENT,FNAME,LNAME,EMAIL,PHONE,FK_RESERVATION) VALUES (#clientId, #fname, #lname, #email, #phone, #reservation"
SqlCommand cmd2 = new SqlCommand(insertSql2, con);
cmd.Parameters.AddWithValue("#clientId", clientId);
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#reservation", **reservationId**);
This will allow you use the Inserted.Id in your second query as you've returned the output to a variable.
Related
SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (ParticipantId, LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#ParticipantId, #LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
// cmd.Parameters.AddWithValue("#ParticipantId", notnull);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender.Text);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
cmd.ExecuteNonQuery();
cnn.Close();
I keep getting the error message:
"System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#ParticipantId".' "
I have tried this multiple ways and have been trying to figure this out for a week now. I'm not understanding what is the bug in my code.
Updated version below:
SqlConnection cnn = new SqlConnection(Properties.Settings.Default.cnnString);
cnn.Open();
cmd = new SqlCommand(#"INSERT INTO Participant (LastName, FirstName, Country, Rank, Gender, IACMember)
VALUES (#LastName, #FirstName, #Country, #Rank, #Gender, #IACMember)", cnn);
//cmd.Parameters.AddWithValue("#ParticipantId", );
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Country", cbHomeCountry.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Rank", txtRank.Text);
cmd.Parameters.AddWithValue("#Gender", txtGender);
cmd.Parameters.AddWithValue("#IACMember", chkMember.Checked);
int nextKey;
cmd = new SqlCommand("SELECT MAX(ParticipantId) FROM Participant", cnn);
nextKey = (int)cmd.ExecuteScalar() + 1;
// cmd.ExecuteNonQuery();
cnn.Close();
if the column ParticipantId is marked as Identity Then You Should Not Try To Manually Insert data in it , sql server will populate it depending on last used ParticipantId , therefore u should remove the column from the insert statement and remove the id parameter .
if its just a Primary Key then u will need to manually insert unique value for each row .
the error mentioned above is because of the commented line which was supposed to provide a value for ParticipantId parameter
I've got my passwords to be hashed in my ASP.NET Webforms.
How do I then enter the hashed password into the database via a string?
SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);
dbCon.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (#firstName, #surname, #email, #username, #passwordHash)", dbCon);
cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
cmd.Parameters.AddWithValue("email", emailTxt.Text);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
cmd.Parameters.ToString("passwordHash");
cmd.ExecuteNonQuery();
I knew I couldn't use .AddWithValue and thought of .ToString may have been the one to use.
I am new to C#.
Thanks.
Does this work?
SqlConnection dbCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConMotorstore"].ConnectionString);
{
dbCon.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [user] VALUES (#firstName,#surname,#email,#username,#passwordHash)", dbCon);
cmd.Parameters.AddWithValue("firstName", firstNameTxt.Text);
cmd.Parameters.AddWithValue("surname", surnameTxt.Text);
cmd.Parameters.AddWithValue("email", emailTxt.Text);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(passwordTxt.Text);
cmd.Parameters.AddWithValue("passwordHash", passwordHash);
cmd.ExecuteNonQuery();
I have to update some values in table row if UserId = Session["username"]
but its showing error:
ExecuteNonQuery: Connection property has not been initialized.
can any one know what i am doing wrong here a Session["username"] have its value i have checked.
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration (FirstName,LastName,Password,LastName,EmaildId,UserId) " +
"VALUES (#FirstName, #LastName, #Password, #EmaildId, #UserId) WHERE UserId='" + Session["username"] + "'";
var cmd = new SqlCommand(qry);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
You need to tell the SqlCommand-object which connection to use, change this line
var cmd = new SqlCommand(qry, conn7);
Two Problems
In SQLCOMMAND you should specify querystring,connection
Your update query syntax is wrong
..try below
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration
SET FirstName=#FirstName,LastName=#LastName,Password=#Password,
EmaildId=#EmaildId,UserId=#UserId WHERE UserId=#UserId1";
var cmd = new SqlCommand(qry,conn7);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId1", Session["username"].ToString());
conn7.Open();
// cmd7.ExecuteNonQuery();
cmd.ExecuteNonQuery();
conn7.Close();
Use Parameters for all you input, don't concatenate strings in queries.
As for your error, you need to specify the connection that the command needs to use:
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;
Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = " UPDATE Registration SET FirstName = #FirstName, LastName = #LastName,"
+ " Password = #Password, EmaildId = #EmaildId WHERE UserId = #UserCondition";
var cmd = new SqlCommand(qry, conn7 );
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserCondition", Session["username"].ToString());
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
'Set' Missing
I created some simple code, but it looks like something is working wrong with my Insert I get error about "where". What did I do wrong?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) where Login =#Login and Password=#Password and Type=#UserType ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
SQL Insert Into statement is
INSERT INTO Table_Name ( Col1, Col2, Col3)
VALUES ( Val1, Val2, Val3);
I think,
insert into dbo.UserInfo (Login, Password, UserType, ID)
where Login =#Login and Password=#Password and Type=#UserType "
try to change the code to this.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType, ID) " +
" VALUES(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
INSERT statements don't have WHERE clauses, UPDATE statements do.
You would only use a WHERE clause if there was an actual select statement.
Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
SELECT Login, Password, UserType, ID
FROM Table
where Login =#Login
and Password=#Password
and Type=#UserType
Otherwise you just use the values. Something like
insert into dbo.UserInfo (Login, Password, UserType, ID)
VALUES (#Login,#Password,#UserType, #ID)
Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Your query should probably be
"insert into dbo.UserInfo (Login, Password, UserType, ID) values (#Login, #Password, #UserType)"
I am not sure why you are using where while inserting single record to table. Below is the proper code to insert
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO UserInfo(Login, Password, UserType) VALUES(#Login,#Password,#Type)";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#Login", TextBox1.Text);
cmd.Parameters.AddWithValue("#Password", TextBox2.Text + ".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}
Please, follow below syntex:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
=============
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.UserInfo (Login, Password, UserType) values(#Login,#Password,#UserType) ", con);
{
cmd.Parameters.AddWithValue("#Login",TextBox1.Text );
cmd.Parameters.AddWithValue("#Password", TextBox2.Text+".123");
cmd.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue);
int rows = cmd.ExecuteNonQuery();
con.Close();
}
Insert syntax is:
INSERT INTO table (column1, column2) VALUES (value1, value2)
Only check your Insert Syntax you will get the answer :
"insert into dbo.xyz(Login, Password, ID) values (#Login, #Password)"
dbo:xyz = your table name
I am new to asp.net. I am executing a simple insert query via a SQL command. Now I want to retrieve the unique id for this newly inserted row and store it in an array. I do not know how to approach this problem.
My code
foreach (GridViewRow gvrow in gvuserdata.Rows)
{
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate", gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
//I want to store ID for this row after insert command
}
Use Select Scope_Identity() with Execute Scalar:
int returnID = 0;
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName,
CarName,Price,startdate,enddate)" + " values(#carid, #username,
#carname,#price,#startdate,#enddate); Select Scope_Identity()";
...
returnID = (int)cmd.ExecuteScalar();
I think your question is how retrieve the newly inserted record in the DB right? if that is the case your can fetch your by using the Scope_Identity()
int returnID = 0;
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate); Select Scope_Identity()";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
SqlDataReader reader = new SqlDataReader();
reader = cmd.ExecuteReader();
returnId = reader("Car_Id_Reference")
Hi Steve Insert one more column in your table with uniqueidentifier as datatype , and add Guid id to the column in codebehind which is uniquely identifiable
to creat GUID
// This code example demonstrates the Guid.NewGuid() method.
using System;
class CreateGUID
{
public static void Main()
{
Guid g;
// Create and display the value of two GUIDs.
g = Guid.NewGuid();
Console.WriteLine(g);
Console.WriteLine(Guid.NewGuid());
}
}
/*
This code example produces the following results:
0f8fad5b-d9cb-469f-a165-70867728950e
7c9e6679-7425-40de-944b-e07fc1f90ae7
*/
Above code is just for your reference to check the unique id generated each time now your code look like below
foreach (GridViewRow gvrow in gvuserdata.Rows)
{
Guid uniqueRowId = Guid.NewGuid();
string strQuery = "insert into vishalc.[Rental Table] (uniqueRowId, Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#uniqueRowId,#carid, #username, #carname,#price,#startdate,#enddate)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#uniqueRowId", uniqueRowId);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate",gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
cmd.CommandType = CommandType.Text;``
cmd.Connection = con;
cmd.ExecuteNonQuery();
//I want to store ID for this row after insert command
}
NOTE: Make sure that you have update the column in the TABLE
Please try adding output parameter and SCOPE_IDENTITY output parameter:
int RetVal = 0;
foreach (GridViewRow gvrow in gvuserdata.Rows)
{
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate);set #out=SCOPE_IDENTITY()";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate", gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
SqlParameter outpar = new SqlParameter("#out", SqlDbType.Int);
outpar.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outpar);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
if (outpar != null)
RetVal = Convert.ToInt32(outpar.Value);
}
Must set the primarykey and Identity="yes" in your column.
Then you can use scopIdentity
string strQuery = "insert into vishalc.[Rental Table] (Car_Id_Reference, UserName, CarName,Price,startdate,enddate)" +
" values(#carid, #username, #carname,#price,#startdate,#enddate); **Select Scope_Identity();**";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#carid", gvrow.Cells[0].Text);
cmd.Parameters.AddWithValue("#username", gvrow.Cells[1].Text);
cmd.Parameters.AddWithValue("#carname", gvrow.Cells[2].Text);
cmd.Parameters.AddWithValue("#price", gvrow.Cells[3].Text);
cmd.Parameters.AddWithValue("#startdate", gvrow.Cells[4].Text);
cmd.Parameters.AddWithValue("#enddate", gvrow.Cells[5].Text);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
**Guid Id=(Guid)(cmd.ExecuteNonQuery());**
See this below line
Guid Id=(Guid)(cmd.ExecuteNonQuery())
You want to guid .So I am converted to guid .