C# Get insert id with Auto Increment - c#

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.

Related

One to many relation data sending

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();
}

C# SQL Server update doesn't work

I have this code, and when I execute it, it doesn't work
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = 'username', pass = '#password' where IDetudient='#ID ' ", con);
con.Open();
cmd.Parameters.AddWithValue("#username", text_name.Text);
cmd.Parameters.AddWithValue("#password",Convert.ToDecimal( textBox1.Text));
cmd.Parameters.AddWithValue("#ID", Convert.ToInt64( text_id.Text));
cmd.ExecuteNonQuery();
con.Close();
Try this way:
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient=#ID", con);
I had the same issue. The thing is, in the query you just pass the name of the parameter.
Your sql command't test would be:
var cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient = #ID ", con);
Also, you will need to validate if conversion from string to int64 if fails or not.

Update table values using cmd.Parameters.AddWithValue not working

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

ExecuteNonQuery doesn't respond?

I want to update some columns on my table but ExecuteNonQuery doesn't respond (Timeout). Did I do something wrong?
Notes: in the database table, id is integer, F1 varchar2 and the parameters I am sending are string and int.
try {
using (OracleConnection con = new OracleConnection(ConString)) {
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE DB.Table "+
"SET F1= :yd" +
"WHERE ID = :id";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("yd", yd);
cmd.Parameters.Add("id", id);
cmd.ExecuteNonQuery();
con.Close();
return true;
}
}
catch (Exception ex) {
return false;
}
Thanks
It can be solved by committing or roll backing pending transactions on your Oracle developer or any other IDEs running on your machine.
You're mixing up your parameter names. There is no parameter named "F1" in your query, use "yd".
cmd.CommandText = "UPDATE DB.Table "+
"SET F1= :yd" +
"WHERE ID = :id";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("yd", yd);
cmd.Parameters.Add("id", id);
I found that is because of other program like toad locks the query. After commiting all thing in toad, everything is solved.
Thanks for all for helping. I love you guys, i like brainstorming :)
cmd.Connection = con;
string qry = "UPDATE DB.Table "+"SET F1= #yd" +"WHERE ID = #id";
OracleCommand cmd = new OracleCommand(qry,con);
cmd.Parameters.AddWithValue("#yd", yd);
cmd.Parameters.AddWithValue("#id", id);
cmd.ExecuteNonQuery();

retrieve unique id for just added row

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 .

Categories

Resources