Syntax Error when writing to my Access database - c#

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

Related

How to upload to Database SQL Server? where is the possible coding error?

string fname=""; <----- Global variable
HtmlInputFile file = (HtmlInputFile)place.FindControl("f_upload");
if (filename.Value.Equals(""))
{
span1.InnerHtml = "<b>Error Message : A File Name must be enter </b>";
return;
}
if (file.PostedFile.ContentLength > 0)
{
try
{
file.PostedFile.SaveAs("c:\\WADUploadFile\\" + filename.Value);
fname = "c:\\WADUploadFile\\" + filename.Value;
//checking fname value
Response.Write(fname);
span1.InnerHtml = "File is uploaded successfully to" + "<b>C:\\WADUploadFile\\" +
filename.Value + "</b>at the server";
}
catch (Exception exc)
{
span1.InnerHtml = "Error occured while saving file to" +
"<b>c:\\WADUploadFile\\" + filename.Value + "</b><br/>" + "[ " +
exc.ToString() + " ]";
}
}
string sql1 = "INSERT INTO Thread (Th_id, Th_poster, Th_date) VALUES (#id, #poster, #date)";
string sql2 = "INSERT INTO ThreadCommend(C_id,C_content,C_upload,T_id,Th_id)Values(#Cid,#Ccontent,#Cupload,#Tid,#Thid)";
con.Open();
SqlCommand cmd1 = new SqlCommand(sql1, con);
cmd1.Parameters.AddWithValue("#id", threadId);
cmd1.Parameters.AddWithValue("#poster", tempPoster);
cmd1.Parameters.AddWithValue("#date", DateTime.Now);
SqlCommand cmd2 = new SqlCommand(sql2, con);
cmd2.Parameters.AddWithValue("#Cid", commendId);
cmd2.Parameters.AddWithValue("#Ccontent", txt);
cmd2.Parameters.AddWithValue("#Cupload", fname.ToString());
cmd2.Parameters.AddWithValue("#Tid", topicId);
cmd2.Parameters.AddWithValue("#Thid", threadId);
//SqlDataAdapter daInsert = new SqlDataAdapter();
//daInsert.InsertCommand = cmdInsertDesc.ToString();
int x = cmd1.ExecuteNonQuery();
con.Close();
con.Open();
int y = cmd2.ExecuteNonQuery(); <--- Error appear here
string note = "Topic added sucussfully";
if (x > 0)
{
Response.Write(note.ToString());
//Response.Write(x.ToString());
}
if (y > 0)
{
Response.Write(note.ToString());
//Response.Write(x.ToString());
}
con.Close();
My question is: how do I upload to the SQL Server database? Is it a problem to ExecuteNonQuery 2 times with each different object?
The error message:
SqlException was unhandled by user code
The parameterized query '(#Cid int,#Ccontent nvarchat(6),#Cupload
nvarchar(4000),#Tid int expects the parameter '#Cupload' which was not
supplied.
What is wrong with my code that I can't add add data to database? T.T
This is an old thread and Im sure you found a fix but it looks like you could have an injection problem. try giving the sqlcommand a data type for each parameter using a SqlDataAdapter.
not sure what your data types are but it should look something like this. Also utilize the using statement so you don't have to close/dispose the connections
using (con)
{
con.Open();
SqlDataAdapter cmd1 = new SqlDataAdapter();
cmd1 = new SqlCommand(sql1, con);
cmd1.InsertCommand.Parameters.Add("#id", SqlDbType.Int).Value = threadId;
cmd1.InsertCommand.Parameters.Add("#poster", SqlDbType.NVarChar).Value = tempPoster;
cmd1.InsertCommand.ExecuteNonQuery();
SqlDataAdapter cmd2 = new SqlDataAdapter();
cmd2 = new SqlCommand(sql2, con);
cmd2.InsertCommand.Parameters.Add("#Cid", SqlDbType.Int).Value = commendId;
cmd2.InsertCommand.Parameters.Add("#Ccontent", SqlDbType.Nvarchar).Value = txt;
cmd2.InsertCommand.Parameters.Add("#Cupload", SqlDbType.Nvarchar).Value = fname.ToString();
cmd2.InsertCommand.Parameters.Add("#Tid", SqlDbType.Int).Value = topicId;
cmd2.InsertCommand.Parameters.Add("#Thid", SqlDbType.Int).Value = threadId;
cmd2.InsertCommand.ExecuteNonQuery();
}

multiple queries on 1 button click

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

How do I delete a row from a Microsoft Access table using c#

I've tried this code:
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =" + textBox1.Text;
OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb");
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.ExecuteNonQuery();
Error: Data type mismatch in criteria expression, at the line:
My_Command.ExecuteNonQuery();
Use parametrized query to avoid all kind of errors
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =?";
using(OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb"))
{
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.Parameters.Add("#p1", textBox1.Text);
My_Command.ExecuteNonQuery();
}
In your case the Room NUmber field is of Text type so, you need to enclose the value in single quotes, but this is really wrong. You expose your code to maliciuos text written by your user inside the text box. A very simple and funny example here
Which type is your [Room Number] column? If it is a string then you have to write the value with inverted comma or quotation mark (I'm not sure which of both is used in Access).
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] = '" + textBox1.Text + "'";
To avoid SQL injektion you should use Parameters instead of the string operation.
public static void DeleteLine(string kv)
{
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
try
{
OleDbConnection con = new OleDbConnection("provider = microsoft.ace.oledb.12.0;data source = E:\\Sohkidatabase\\Sohki.accdb");
con.Open();
str = "select * from compny_info where id=" + comboBox1.Text.Trim() + "";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
if (reader.Read())
{
textBox1.Text = reader["regis_no"].ToString();
textBox2.Text = reader["comp_oner"].ToString();
textBox3.Text = reader["comp_name"].ToString();
textBox4.Text = reader["comp_add"].ToString();
textBox5.Text = reader["tin_no"].ToString();
textBox6.Text = reader["email"].ToString();
}
con.Close();
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
public static void DeleteLine(string kv) {
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'" ;
}

How to run multiple SQL commands in a single SQL connection?

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.

It says command.ExecuteNonQuery() is not initialized

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

Categories