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();
//...
}
}
Related
I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)
Is that correct way of reading data from table then insert into table ?
I am trying to read the max number or rec_id to create seq column the +1 to insert my data record into same table
//Opening the connection with Oracle Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
//Create the oracle statment and insert data into oracle database
OracleCommand cmd1 = new OracleCommand();
cmd1.Connection = conn;
cmd1.CommandText = "SELECT NVL (MAX (rec_id), 0) + 1 FROM backup_check";
OracleDataReader dr = cmd1.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
conn.Dispose();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
//OracleTransaction trans = conn.BeginTransaction(); -- add rollback in case of transaction not complate for some reason
cmd.CommandText = "insert into my table(" + "'" + v_rec_id + "'" + ",OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null," + "'" + keyword + "'" + ",'0','abc',sysdate)";
cmd.ExecuteNonQuery();
//Closing the connection with oracle databae
conn.Dispose();
First of all, you should forget to use the MAX function to retrieve the next value to insert in an 'so called autoincrement column'. The problem arises from the fact that your code running on one machine cannot prevent another user from another machine to execute the same code concurrently with yours. This could result in both users receiving the same MAX result and thus creating invalid duplicate keys.
In Oracle you should mark your table to have a SEQUENCE for your primary key (REC_ID)
Something like this (writing here on the fly not tested now....)
CREATE TABLE myTable
(
rec_id NUMBER PRIMARY KEY
.... other columns follow
);
CREATE SEQUENCE myTable_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20;
CREATE OR REPLACE TRIGGER myTable_trg
BEFORE INSERT ON myTable
for each row
begin
select myTable_seq.nextval into :new.rec_id from dual;
end;
At this point, when you try to insert a new record the triggers kicks in and calculate the next value to assign to your primary key.
The C# code is simplified a lot and becomes:
string cmdText = #"insert into myTable
(OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)
values(null,:keyw,'0','abc',sysdate)";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand(cmdText, conn))
{
conn.Open();
//using(OracleTransaction trans = conn.BeginTransaction())
//{
cmd.Parameters.AddWithValue(":keyw",keyword);
cmd.ExecuteNonQuery();
// trans.Commit();
//}
}
No need to read anything before, command text not concatenated avoid SQL Injection, closing and disposing is automatic exiting from the using block....
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();
}
I've created a database and a table with 2 fields Id and Name.
Now I want to insert values on clicking a button the sammple code is given. it's not working.
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command =new SqlCommand("insert into Test (Id,Name) values(5,kk);",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
String values should be in quotes. This has not much to do with C#, more with T-SQL
Try this, and notice the kk;
SqlCommand command =
new SqlCommand("insert into Test (Id,Name) values(5,'kk');",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Also I am assuming here that Id is not an auto-increment field. If it is, then you should not fill it.
As a side-node you should look at parameterized queries to prevent SQL injection.
In this instance, you need single quotes ' around the kk
insert into Test (Id,Name) values(5,'kk')
In general, you should use parameterised queries
try this:
SqlConnection conn = new SqlConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand("insert into Test (Id,Name) values(#iD, #Name)", conn, trans))
{
cmd.CommandType = CommandType.Text;
cmd.AddParameter(SqlDbType.UniqueIdentifier, ParameterDirection.Input, "#iD", ID);
cmd.AddParameter(SqlDbType.VarChar, ParameterDirection.Input, "#Name", Name);
cmd.ExecuteNonQuery();
}
conn.CommitTransaction(trans);
}
catch (Exception ex)
{
conn.RollbackTransaction(trans);
throw ex;
}
Try this:
SqlConnection con = new SqlConnection('connection string here');
string command = "INSERT INTO Test(Id, Name) VALUES(5, 'kk')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
String values should be between ' '
Verify your connection string
//add your connection string between ""
string connectionString = "";
using (var conn = new SqlConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO pdf (Id, Name) VALUES (5, 'kk')";
conn.Open();
conn.ExecuteNonQuery();
conn.Close();
}
It looks like you have multiple problems with your current code.
You need to enclose string values in single quotes, as pointed out in other answers.
You need to enable remote connection to your SQL server.
Check the following link if you are using SQL server 2008.
How to enable remote connections in SQL Server 2008?
and for SQL Server 2005 see:
How to configure SQL Server 2005 to allow remote connections
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.