My code:
// Get Connection String
string conn = WebConfigurationManager.ConnectionStrings["GraduatesConnectionString"].ToString();
// Create connection object
SqlConnection connection = new SqlConnection(conn);
SqlCommand command = connection.CreateCommand();
try
{
// Open the connection.
connection.Open();
// Execute the insert command.
command.CommandText = ("INSERT INTO PersonalInfo(Id,Name,LastName,ContactNumber, Address,Gender, Date_Of_Birth) VALUES(\'"
+ (this.txtID.Text + ("\',\'"
+ (this.txtName.Text + ("\',\'"
+ (this.txtLastName.Text + ("\',\'"
+ (this.txtContactNumber.Text + ("\',\'"
+ (this.txtAddress.Text + ("\',\'"
+ (this.gender + ("\',\'"
+ (this.txtDateofBirth.Text + ("\',\'"
)))));
command.ExecuteNonQuery();
}
finally
{
// Close the connection.
connection.Close();
}
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO PersonalInfo (Id, Name, LastName, ContactNumber, Address, Gender, Date_Of_Birth) VALUES (#Id, #Name, #LastName, #LastName, #Address, #Gender, #DateOfBirth)";
command.Parameters.AddWithValue("#Id", txtID.Text);
...
connection.Open();
command.ExecuteNonQuery();
}
You are missing a closing ) after txtDateofBirth so your statement is incomplete.
BUT please take note of the comment of #podiluska. This code is really easy to abuse. Suppose I enter something like the following text in txtDateofBirth:
;DROP TABLE PersonalInfo;
You then get a query like:
INSERT INTO PersonalInfo(...)
VALUES (...);DROP TABLE PersonalInfo;
So please use parameterized queries as described by #abatishchev.
I'd be tempted to change your code to:
string conn = WebConfigurationManager.ConnectionStrings["GraduatesConnectionString"].ToString();
// Create connection object
using(SqlConnection connection = new SqlConnection(conn))
{
string queryText = "INSERT INTO PersonalInfo(Id,Name,LastName,ContactNumber, Address,Gender, Date_Of_Birth) VALUES(#id,#name,#lastName,#contactNumber, #address,#gender, #date_Of_Birth)";
using(SqlCommand command = new SqlCommand(queryText, connection))
{
try
{
// Open the connection.
connection.Open();
command.Parameters.AddWithValue("#id", this.txtID.Text);
command.Parameters.AddWithValue("#name", this.txtName.Text);
command.Parameters.AddWithValue("#lastName", this.txtLastName.Text);
command.Parameters.AddWithValue("#contactNumber", this.txtContactNumber.Text);
command.Parameters.AddWithValue("#address", this.txtAddress.Text);
command.Parameters.AddWithValue("#gender",this.gender );
command.Parameters.AddWithValue("#date_Of_Birth", this.txtDateofBirth.Text);
command.ExecuteReader();
}
finally
{
// Close the connection.
if(connection.State != ConnectionState.Closed)
connection.Close();
}
}
}
Related
I got this code inside a method:
string tableName = "messages_user-test";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\janke\\source\\repos\\Unichat\\Unichat\\bin\\Debug\\history.accdb;Persist Security Info=False;");
conn.Open();
OleDbCommand comm = new OleDbCommand();
comm.Connection = conn;
string writestring = "insert into " + tableName + " ([from], [to], [datetime], [message]) values (#from, #to, #datetime, #message);";
Console.WriteLine(writestring);
comm.CommandText = writestring;
comm.Parameters.AddWithValue("#from", from);
comm.Parameters.AddWithValue("#to", to);
comm.Parameters.AddWithValue("#datetime", date);
comm.Parameters.AddWithValue("#message", text);
comm.ExecuteNonQuery();
comm.Dispose();
conn.Close();
When I execute the program I get this error at comm.ExecuteNonQuery();
System.Data.OleDb.OleDbException: "Syntaxerror in INSERT INTO statement."
I am pretty new to OleDB and I have already read hundreds of threads about this error but nothing worked for me.
Using square bracket for table name and field name
Maybe the date (from, to, date) value that causing the error
Don't forget to add try..catch
Check the profiler for more detail
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\janke\\source\\repos\\Unichat\\Unichat\\bin\\Debug\\history.accdb;Persist Security Info=False;"))
{
string strFeedback = "";
string tableName = "messages_user-test";
string writestring = string.Format("INSERT INTO [{0}] ([from], [to], [datetime], [message]) VALUES (#from, #to, #datetime, #message);", tableName);
OleDbCommand comm = new OleDbCommand(writestring);
comm.Parameters.Add(new OleDbParameter("#from", from.ToString("yyyy-MM-dd")));
comm.Parameters.Add(new OleDbParameter("#to", to.ToString("yyyy-MM-dd")));
comm.Parameters.Add(new OleDbParameter("#date", date.ToString("yyyy-MM-dd HH:mm:ss")));
comm.Parameters.Add(new OleDbParameter("#message", text));
try
{
strFeedback = comm.ExecuteNonQuery().ToString() + " record has been added successfully!";
}
catch (Exception ex)
{
strFeedback = "ERROR: " + err.Message;
}
}
Not able to insert date into datetime column in sql server.
While debugging after the first executeNonQuery() statement debugger jumps to catch block
and it's displaying the following message in sqlError parameter in catch block:
'Incorrect Syntax near 12'
public ActionResult AddStudentData(StudentDetails sd)
{
SqlConnection db = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\StudentDB.mdf;Integrated Security=True;User Instance=True");
SqlTransaction transaction;
db.Open();
transaction = db.BeginTransaction();
SqlCommand cmd = db.CreateCommand();
try
{
**cmd.CommandText = "insert into StudentDetails(StudentName, DOB, Description, Gender) values ('" + sd.StudentName + "'," +sd.DOB + ",'" + sd.Description + "','" + sd.Gender + "')";
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();**
cmd.CommandText = "select max(StudentID) from StudentDetails";
int id = (int)cmd.ExecuteScalar();
cmd.CommandText = "insert into Qualification (StudentID, Qualification, POY) values ("+id+",'"+sd.Qualification+"',"+sd.POY+")";
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
transaction.Commit();
}
catch (SqlException sqlError)
{
string s = sqlError.Message.ToString();
transaction.Rollback();
}
db.Close();
return View("SuccessAddStudentData");
}
Thank You
Dilipkumar
Note that date values (DOB) must also contain single quotes.
cmd.CommandText = "insert into StudentDetails(StudentName, DOB, Description, Gender)
values ('" + sd.StudentName + "','" +sd.DOB + "','" +
sd.Description + "','" + sd.Gender + "')";
Also, keep in mind the date format based on SQL Server.
And lastly as other posts mentioned, use bind parameters to prevent SQL injection.
You should ALWAYS use parameterized queries when accessing a SQL database, otherwise your application might be vulnerable to SQL injection. You also should use using when dealing with objects for database access. For example, when the using block is left, the connection will be closed no matter if an exception was thrown or not.
try
{
using (var db = new SqlConnection("connection string"))
using (var transaction = db.BeginTransaction())
using (var cmd = db.CreateCommand())
{
cmd.Transaction = transaction;
db.Open();
cmd.CommandText = "insert into StudentDetails(StudentName, DOB, Description, Gender) values(#name, #dob, #desc, #gender)";
cmd.Parameters.AddWithValue("#name", sd.StudentName);
cmd.Parameters.AddWithValue("#dob", sd.DOB);
cmd.Parameters.AddWithValue("#desc", sd.Description);
cmd.Parameters.AddWithValue("#gender", sd.Gender);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
// other queries
transaction.Commit();
}
}
catch (SqlException ex)
{
string s = ex.Message.ToString();
}
I want to perform 2 queries in one button click. I tried the
string query = "first query";
query+="second query";
But this didn't work it shows error.
I have now created 2 separate connections like below:
try
{
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
//open connection with database
conn1.Open();
//query to select all users with teh given username
SqlCommand com1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", conn1);
// comand.Parameters.AddWithValue("#id", iD);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute queries
com1.ExecuteNonQuery();
conn1.Close();
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com2 = new SqlCommand("insert into artikulli(path) values ('" + filename + "')", conn2);
//open connection with database
conn2.Open();
com2.ExecuteNonQuery();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni perzgjedhur asnje file');", true);
}
}
But the problem is that only the second query is performed and the firs is saved as null in database
In your case, there is no reason to open two connections. In addition, the C# language has evolved, so I recommend using the power given by the new language constructs (using, var).
Here is an improved version that should work assuming that the values you bind to your parameters are valid:
try
{
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString))
{
//open connection with database
connection.Open();
//query to select all users with teh given username
using(var command1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", connection))
{
command1.Parameters.AddWithValue("#tema", InputTitle.Value);
command1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
command1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
command1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute first query
command1.ExecuteNonQuery();
}
//build second query
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
using(SqlCommand command2 = new SqlCommand("insert into artikulli(path) values (#filename)", connection))
{
//add parameters
command2.Parameters.AddWithValue("#filename", filename);
//execute second query
command2.ExecuteNonQuery();
}
}
}
//TODO: add some exception handling
//simply wrapping code in a try block has no effect without a catch/finally
Try below code, No need to open the connection twice
string query1 = "insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com1= new SqlCommand(query1, conn);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
string query2 = "insert into artikulli(path) values ('" + filename + "')", conn);
comm.ExecuteNonQuery();
comm.CommandText = query2;
comm.ExecuteScalar();
string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, Sur-Name, Score,Avg) VALUES ('" + fName + "','" + sName + "','" + lblScore.Text + "','" + lblAvg.Text + "');");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#Sur-Name", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
finally
{
connection.Close();
}
The error I keep getting is a runtime saying
Incorrect syntax near '-'. Incorrect syntax near '-'.
I used the try catch just so page would load and my scores show but the label says this Incorrect syntax as well, I was wondering could anyone please help me with what I am doing wrong
Thanks.
I think Sur-Name breaks your query. Use it with square brackets like [Sur-Name]
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. I see you tried to use but you never declare your parameter names in your query.
Also DATA might be a reserved keyword on future versions of SQL Server. You might need to use with also like [DATA]
Consider to use using statement to dispose your SqlConnection and SqlCommand.
using(SqlConnection connection = new SqlConnection(ConnectionString))
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = #"INSERT INTO [Data] (Name, [Sur-Name], Score, Avg)
VALUES (#Name, #SurName, #Score, #Avg)";
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
}
You are trying to mix concatenated queries with parametrized. Always use parametrized queries, It will save you from SQL Injection.
SqlCommand cmd = new SqlCommand(#"INSERT INTO [Data] (Name, [Sur-Name], Score,Avg) VALUES (
#Name, #SurName, #Score, #Avg)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
Also consider enclosing your connection and command object in using statement.
As #Soner has mentioned in his answer, use Square brackets for Data and Sur-Name
I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.