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 .
Related
I am unable to send lasted inserted autoincrement id value to another table
this is my code
i am getting error is Must declare the scalar variable "#userid".
int ID;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()", cn);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
cmd.ExecuteNonQuery();
ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
SqlCommand cmd2 = new SqlCommand("insert into sampfk values(#emailid,#address,#userid)", cn);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text);
cmd2.Parameters.AddWithValue("#userid", ID);
cn.Open();
cmd2.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
TextBox3.Text = "";
TextBox4.Text = "";
I think I got your problem.you have written
SqlCommand cmd2 = new SqlCommand("insert into sampfk values (#userid, #address, #emailid)", cn);
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text)
but executing
cmd2.ExecuteNonQuery();
you should add parameter in cmd2 not cmd like as
cmd2.Parameters.AddWithValue("#userid", ID);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text)
You can do above in single step, you should use using more and try to nest query if possible. Opening TCP connection frequently has some acknowledgement overheads.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString))
{
string query = #"INSERT INTO sampdb VALUES (#name,#phone);
INSERT INTO sampfk VALUES (SCOPE_IDENITTY(), #address, #emailid); ";
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Check the following line.
ID = Convert.ToInt32(cmd.ExecuteScalar());
If this doesn't return anything, then use a default value for ID, maybe 0.
Or add a default value in the declaration as int id = 0;
try this
using (SqlConnection cn = new SqlConnection(connectionStr))
{
string sql1 = "insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()";
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
ID = cmd.ExecuteNonQuery();
}
//ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
string sql2 = "insert into sampfk values (#userid, #address, #emailid)";
using (SqlCommand cmd = new SqlCommand(sql2, cn))
{
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
con.Dispose();
con.Close();
}
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 use this code to update data that are in the textboxes... this code is in the update button and once i made the changes and clicked the button the error message appears
try
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE student_info SET SEM = #SEM, STUDENT_NO = #STUDENT_NO, LASTNAME = #LASTNAME" +
", FIRSTNAME = #FIRSTNAME, MIDDLENAME = #MIDDLENAME, CITY = #CITY, STREET = #STREET, GENDER = #GENDER" +
", COURSE = #COURSE, YEAR = #YEAR, SECTION = #SECTION, BIRTHDAY = #BIRTHDAY Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#SEM", sem_combo.Text);
cmd.Parameters.AddWithValue("#STUDENT_NO", studentNo_txt.Text);
cmd.Parameters.AddWithValue("#LASTNAME", lname_txt.Text);
cmd.Parameters.AddWithValue("#FIRSTNAME", fname_txt.Text);
cmd.Parameters.AddWithValue("#MIDDLENAME", mname_txt.Text);
cmd.Parameters.AddWithValue("#CITY", address_txt.Text);
cmd.Parameters.AddWithValue("#STREET", street_txt.Text);
cmd.Parameters.AddWithValue("#GENDER", gender_combo.Text);
cmd.Parameters.AddWithValue("#COURSE", program_combo.Text);
cmd.Parameters.AddWithValue("#YEAR", yr_combo.Text);
cmd.Parameters.AddWithValue("#SECTION", section_combo.Text);
cmd.Parameters.AddWithValue("#BIRTHDAY", bday.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL, CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Check in This Line
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL,
CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
Change To
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL,
CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.Parameters.AddWithValue("#STUDENT_NOL",studentNo_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
you are clear the parameters, but after that use #STUDENT_NO parameter. This parameter is not declare any where after clear ther parameters
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.
I am using this method to insert a row into a table:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) VALUES" +
"(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
I hav also id column that have Auto Increment .
And i want to know if it possible to get the id that is created when i insert a new row.
You can access the MySqlCommand LastInsertedId property.
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) "
+ "VALUES(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
**cmd.Parameters["#clientid"].Direction = ParameterDirection.Output;**
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Basically you should add this to end of your CommandText:
SET #newPK = LAST_INSERT_ID();
and add another ADO.NET parameter "newPK". After command is executed it will contain new ID.