Weird error in "insert into" command? - c#

I know this may sound rubbish but that's the truth.
everytime when i try to run this code i get syntax error.
any idea why?
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Rock.accdb";
con.Open();
String query = "insert into category ([name],desc) values (#1,#2)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#1", textBox1.Text);
cmd.Parameters.AddWithValue("#2", textBox2.Text);
cmd.ExecuteNonQuery();
textBox1.Text = null;
textBox2.Text = null;
label4.Text = "New Category Created";
label4.ForeColor = Color.Green;
the error is: Syntax error in INSERT INTO statement # cmd.ExecuteNonQuery();

desc is also a keyword (for descending) and so you'd need:
String query = "insert into category ([name],[desc]) values (#1,#2)";

Change your insert query like this,
String query = "insert into category ([name], [desc]) values (#1,#2)";
desc is reserved word by default. Also, please close your connection by con.Close(); after executing the command.

Related

Syntax error in UPDATE statement while updating password in Access database

I faced syntax error in UPDATE statement, while updating password in Access database in C#:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE into userdata(password)values('"+TextBox1.Text+"') where id=#id";
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
}
It's because your SQL Query is not correct, that's not how you update data in your database. It should be like this:
query = "Update [tableName] SET [ColumnName] = 'Values', [ColumnName1] = 'Values2',...";
You should learn at least the basics of SQL syntax, more information here
And also, you shouldn't concatenate your query since it will become vulnerable for SQL Injection attack, you should at least use Parameterized Query
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE yourTableName SET [yourColumnName] = #YourFirstValue, [secondColumnName] = #YourSecondValue WHERE [columnKey] = #ID"
cmd.Parameters.AddWithValue("#YourFirstValues", textbox1.Text);
cmd.Parameters.AddWithValue("#YourSecondValue ", textbox2.Text);
cmd.Parameters.AddWithValue("#ID", textbox3.Text);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
you have to fix your query
"UPDATE userdata SET password=#password where id=#id";
and add new lines before cmd.ExecuteNonQuery()
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
I had a similar problem, it gave me a syntax error that I solved by checking the whole string and actually there was a comma too many, I don't know if this answer of mine can be useful, among other things after some time.

Adding a Where Clause to a OleDbCommand

I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);

Adding rows to a SQL Server database from data entered by user in asp.net c#

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

Whats wrong with my MS Access Update Query?

Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....

"Data type mismatch in criteria expression" when trying to delete row from database

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

Categories