I have two tables, one containing names, and one containing rates and other data that is lined to each name. After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates.
How can I do this? I read about scope_identity online but I'm not sure how to use it.
This is what I have so far:
SqlConnection con = new SqlConnection(pubvar.x);
SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";
SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";
SELECT SCOPE_IDENTITY();
con.Open();
command.ExecuteNonQuery();
con.Close();
Considering the case you've described, I don't see any need to return the identity from the database. You can simply issue both statements in one command:
using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
Connection = cnx,
CommandText = #"
insert into A (Name) values (#name)
insert into B (A_ID, Rate) values (scope_identity(), #rate)
",
Parameters =
{
new SqlParameter("#name", name),
new SqlParameter("#rate", .5m) //sample rate
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
Related
I am writing a sample application to insert data into a SQL Server database using C#. Data is not persisting in the database.
Below is my code:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Insert into Record (ID,Name) values ('" + txtId.Text + "' , '" + txtName.Text + "')";
cmd.ExecuteNonQuery();
//cmd.Clone();
conn.Close();
The values are not persisted. There is no error when I insert the values. When I changed my command to:
"Insert into Database.dbo.Record (ID,Name) values ('"
it throws an exception:
Incorrect syntax near the keyword 'Database'.
Why is my SQL Server database not being updated?
Your code as is, is possibly open to SQL injection - you should use parameters.
Also check the table names and primary keys, e.g. if ID is an Identity column it is automatically generated when you insert, so then you'll just INSERT INTO Record (Name) VALUES ('Bob')
Otherwise if ID is a primary key you'll likely have to check you are not trying to insert duplicates.
Please use parameters! (adjust the SqlDbType's if needed)
You should also use a using statement over the connection to properly dispose resources, and ideally use a transaction for updates:
string sqlQuery = "INSERT INTO Record (ID, Name) VALUES (#id, #name); ";
using (SqlConnection conn = new SqlConnection(connectionString)) {
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try {
SqlCommand command = new SqlCommand(sqlQuery, conn, tran);
SqlParameter in1 = command.Parameters.Add("#id", SqlDbType.NVarChar);
in1.Value = txtId.Text;
SqlParameter in2 = command.Parameters.Add("#name", SqlDbType.NVarChar);
in1.Value = txtName.Text;
command.ExecuteNonQuery();
tran.Commit();
} catch (Exception ex) {
tran.Rollback();
//...
}
}
I have a ms-access database that has some tables, using C# I insert their values but at the end I want to collect data from each one of them and put these data to another table.
these is my tables:
this is how I insert FeedID from tFeeds into tFeedsRation:
{
string StrCon = System.Configuration....;
string InsertInto = #"INSERT INTO tFeedsRations
SELECT FeedID FROM tFeeds
WHERE tFeeds.FeedID=#id";
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
Connection.Open();
Cmd.CommandText = InsertInto;
Cmd.Parameters.Add("#id", OleDbType.Integer).Value = SelectedFeedID;
Cmd.ExecuteNonQuery();
Connection.Close();
}
Now my question is:
First I want to insert RationID from tRations into tFeedsRations in a same time,
And after that I want to insert these data to tFeedsRationsCows:
FeedID from tFeedsRations
RationID from tRations
CowID from tCows
I'm getting a syntax error in INSERT INTO statement and I can't figure out why. I've checked several different SO questions that were almost exactly the same as my problem and after changing my code this way and that way it still isn't working.
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", oldDb);
var cnn = new OleDbConnection(cnnStr);
cnn.Open();
//make new access table
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = cnn;
command.CommandText = String.Format("CREATE TABLE [{0}] ([Tag] string, [Text] string)", newTable + "_Diff");
try
{
command.ExecuteNonQuery();
}
catch
{
//table already exists
}
}
//fill access table
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = cnn;
command.CommandText = String.Format("INSERT INTO [{0}] (Tag, Text) VALUES (?, ?)", newTable + "_Diff");
command.Parameters.Add(new OleDbParameter("Tag", ""));
command.Parameters.Add(new OleDbParameter("Text", ""));
for (int i = 0; i < (diffText.Length - 1); i++)
{
command.Parameters["Tag"].Value = diffTag[i];
command.Parameters["Text"].Value = diffText[i];
command.ExecuteNonQuery();
}
}
cnn.Close();
Creating the table is working so I know there's not a problem with my connection, there's just something it doesn't like about my insert statement.
In your insert command put text inside a square bracket, "text" is a keyword
command.CommandText = String.Format("INSERT INTO [{0}] (Tag, [Text])
VALUES (?, ?)", newTable + "_Diff");
also make sure you are including your values with single quote
values ('?','?')
hope this works
i have database in access with auto increase field (ID).
i insert record like this (in C#)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
how to get the last inserting number ?
i dont want to run new query i know that in sql there is something like SELECT ##IDENTITY
but i dont know how to use it
thanks in advance
More about this : Getting the identity of the most recently added record
The Jet 4.0 provider supports ##Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
I guess you could even write an extension method for OleDbConnection...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
I like more indicate the type of command
is very similar to the good solution provided by Pranay Rana
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("#CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
Using #Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:
OleDbConnection con = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.
Simple,
What we do in excel for copy text in above cell?
Yes, just ctrl+" combination,
and yes, it's work in MS ACCESS also.
You can use above key stroke combination for copy above records field text, just make sure if you have duplicate verification applied or edit field data before move next field.
If you aspects some more validation or any extraordinary then keep searching stack overflow.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID); SELECT CAST(scope_identity() AS int)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
int lastID = (int)command.ExecuteScalar();
}
Without the
SELECT CAST(scope_identity() AS int)
One row is inserted. But since I need the ID from the created row im using scope_identity. However, when I use this, 2 rows are created instead of one.
Did I miss something?
Thanks
The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();
If you try to use only the executeScalar i think you have the result's you want....
Try and hope this helps...
If you want you can use Parameter to retrieve the Identity, like they do in this Article
If you would use gbn or my answer from your first question, the problem shouldn't occur.
Try doing
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID);";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
query = "SELECT CAST(scope_identity() AS int)";
command = new SqlCommand(query, connection);
int lastID = (int)command.ExecuteScalar();
}