I'm trying to execute a very simple SQL statement on an Access database through C#.
The statement is something like this:
select M_PASSWORD from TB_USERS where M_USERNAME = 'myuser'
and this is the C# code I'm using to execute the SQL statement:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sources.global_variables.db_source;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT #1 from #2 WHERE #3='#4'", connection);
command.Parameters.AddWithValue("#1", db_column);
command.Parameters.AddWithValue("#2", db_table);
command.Parameters.AddWithValue("#3", db_where_column);
command.Parameters.AddWithValue("#4", db_where_value);
reader = command.ExecuteReader();
//rest of code
Once I get to the line reader = command.ExecuteReader();, the reader fails the execution of the query giving me the following error message: OleDBException was unhandled: Syntax error in query (Incomplete query clause).
I've debugged the code to see if I could see any wrong assignment in the parameters values, but they look fine.
Moreover, executing the exact same query on the Query Analyzer of the Database, I retrieve the value I want.
Could anyone give a tip to spot the problem and understand where I'm wrong?
I think you cant pick column names as parameter such that. It might be the problem.
Use if statement or other conditional statements for parameter and move your query to inside of your conditional statement.
I don't believe that parameters can be used in the fashion you posted. Parameters are used for filling in values (ie, placing a DateTime value into an update statement as the value of a DateTime column to be updated in a table).
Try changing your code such that the column names and table names are provided in text or are filled in as a string. You can build the query string up if you want to fill in different column names, different table names, and different column names in your where clause. So instead of what you posted, try something more like this:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sources.global_variables.db_source;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
string strQuery = "SELECT " + constStringColumnName1 + " FROM " + theTableNamePassedInAsString + " WHERE " + strWhereClauseBuiltEarlierInThisFunction + " = '#1'";
OleDbCommand command = new OleDbCommand( strQuery , connection);
command.Parameters.AddWithValue("#1", db_where_value);
reader = command.ExecuteReader();
//rest of code
}
Of course, you could format the string and plug in your changing selection column name, your table name, and your where clause. Build your select/command string, then use Parameters to fill in the actual value is the normal usage.
Try remove the ' on where parameter and use ? insted of # like that
OleDbCommand command = new OleDbCommand("SELECT ? from ? WHERE ?=?", connection);
command.Parameters.AddWithValue("column", db_column);
command.Parameters.AddWithValue("table", db_table);
command.Parameters.AddWithValue("where_column", db_where_column);
command.Parameters.AddWithValue("where_value", db_where_value);
I dont know if you can use parameters on column name. If it won´t running try to execute the query without parameters using concat and only use parameters on where value
Related
I was creating an Appointment Table and i want to check if the row contains same Date,Slot,HR exists before another user enter.
The Connection is Opened Before this shown code.
SqlCommand slot_check = new SqlCommand("select * from Appointment where AppoinmentDate='"+textBox1.Text+"' and Slot='"+comboBox3.Text+ "'and HRName='" +comboBox2.Text+"'");
SqlDataReader Exist = slot_check.ExecuteReader();
if (Exist.HasRows)
{
string message = "Appointment Already Exists!!!!!";
MessageBox.Show(message);
}
else
{
string message = "Update";
MessageBox.Show(message);
}
System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.'
To execute a command two informations are essential:
The sql string to execute and the connection to reach the database.
Without the connection your command cannot be executed because the framework doesn't know how to read or write the database.
There is an overload for the SqlCommand constructor that takes the two required parameters:
SqlCommand cmd = new SqlCommand(sqlText, connectionInstance);
So your code should be something like this
// The command text to run, without string concatenations and with parameters placeholders
string sqlText = #"select * from Appointment
where AppoinmentDate=#aptDate
and Slot=#slot
and HRName=#name";
// Using statement to correctly close and dispose the disposable objects
using(SqlConnection cnn = new SqlConnection(connectionString))
using(SqlCommand slot_check = new SqlCommand(sqlText, cnn))
{
// A parameter for each placeholder with the proper datatype
cmd.Parameters.Add("#aptDate", SqlDbType.Date).Value = Convert.ToDateTime(textBox1.Text);
cmd.Parameters.Add("#slot", SqlDbType.NVarChar).Value = comboBox3.Text;
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = comboBox2.Text;
cnn.Open();
// Even the SqlDataReader is a disposable object
using(SqlDataReader Exist = slot_check.ExecuteReader())
{
if (Exist.HasRows)
{
string message = "Appointment Already Exists!!!!!";
MessageBox.Show(message + " " + Exist + comboBox2.Text);
}
else
{
string message = "Update";
MessageBox.Show(message);
}
}
}
As you can see the code now has a connection passed to the command constructor and a command text built without concatenating strings but using parameters.
Using parameters is a mandatory approach for any kind of database related operation. Without parameters your code could be exploited with the well known Sql Injection hack, but also, the simple presence of a single quote in your values, could break the sql syntax resulting in a Syntax Error Exception
Note that this code could still be wrong because I don't know what kind of data is stored in your table in the columns used in the WHERE statement. I assumed some kind of type but you should check against your table and verify if they are correct.
I'm having problems with some code I'm trying to write. I'm doing something for suppliers orders, so I have a table which is named "encomendas_fornecedores" with a autoincrement field before the key that is the code of sale which consists in a EF before the number(which is a text field).
Here is the code:
connection.Open();
OleDbCommand comando1 = new OleDbCommand();
OleDbCommand comando2 = new OleDbCommand();
OleDbCommand comando3 = new OleDbCommand();
comando1.Connection = connection;
comando2.Connection = connection;
comando3.Connection = connection;
comando1.CommandText = "INSERT INTO encomendas_fornecedores (cod_encomenda_forn, cod_metodo, cod_forn, total_pagar_forn) VALUES('FO', '" + txtcodmetodo.Text + "', '" + txtcodforn.Text + "', '" + lbltotalapagar.Text + "'); ";// insert into table the values with a FO to cod
comando1.ExecuteNonQuery();
comando2.CommandText = "Select MAX(num_encomenda) From encomendas_fornecedores;";// selecting maximum num encomenda so I can isolate it and add to a text before(btw I do this in php/sql no problems
int numero = Convert.ToInt32(comando2.ExecuteScalar());//max num_encomenda
string codencomendaforn= "EF"+Convert.ToString(numero);// sales code completed
comando3.CommandText = "UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = '"+ numero +"';";//query that is giving me the problems, it says something like "type of data incorrect in data expression"
comando3.ExecuteScalar();//giving me error this line
connection.Close();
But now here's the catch the cod_encomenda_forn is text and the num_encomenda auto increment as it is in the sql, and I tried to show the query in a textbox to see if its anything is wrong but nothing seems wrong.
"UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = **'**"+ **numero** +"**'**;";//query that is giving me the problems,it says something like "type of data incorrect in data expression"
You are passing a string numero to a where statement that seems like it is expecting a number. As long as it is numeric it should work, but definitely not gauranteed to work. Second you are passing anothercodencomendaforn string to encomenda what is encomenda 's data type?
It appears that you are not handling potential datatype differences between your c# code and your SQL query. In addition single quoting '' around a value in a SQL statement tells the database engines that it is a string even if that is '1234'. While SQL will automatically convert some values it doesn't always. In addition c# .net library also looks for some conversion etc. before sending the SQL statement. To fix appropriately use parameters that are data typed to the database type in the SQL table. To fix it simply in the statement figure out your data types and fix the '' single quotes appropriately.
PS the people trying to help you in the comments were being nice and telling you the professional way of keeping your job in the future when you graduate after fixing this issue.
I'm trying to optimise the code for an insert statement in SQLite.
I have a problem when inserting multiple values into SQLite from C# Application.
If I try this directly into SQL:
INSERT INTO TBL4 (ID,zID,d) VALUES (6144,1,1),(6144,1,2);
the statement writes two rows of data into table name TBL4.
But, if I want to use this statement in c# and execute it, I have some errors getting from database (error is random.)
Here is the code from c#:
//this is just db connection
string connstr = "Data Source = "+frm.basedir+";"+frm.basever+";";
SQLiteConnection conn = new SQLiteConnection(connstr);
conn.Open();
//working code, successful inserted data into SQL
//g and d variable contain values: 6144 and 2
string sql3 = "INSERT INTO tbl3 (id,d) values (" + g + "," + d + ")";
SQLiteCommand comm3 = new SQLiteCommand(sql3, conn);
comm3.ExecuteNonQuery();
//not working code, throws an error
string sql4 = "INSERT INTO tbl4 (ID,zID,d) VALUES (6144,1,1),(6144,1,2)";
SQLiteCommand comm4 = new SQLiteCommand(sql4, conn);
comm4.ExecuteNonQuery();
My SQLitedatabse is 3.8 version.
Thank in advance
I am trying to update data in access table. However, i keep receiving a syntax error when i attempt to update. Below is the code ive compiled. Textbox37 is the one that requires updates.
string constr1;
constr1 = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Documents\\data.accdb;Jet OLEDB:Database";
string cmdstr = "Update Log(Notes,Status)Values(#a,#b) Where LogIncNum='" + LogInc + "'";
using (OleDbConnection con1 = new OleDbConnection(constr1))
{
using (OleDbCommand com = new OleDbCommand(cmdstr, con1))
{
com.CommandType = CommandType.Text;
com.Parameters.AddWithValue("#a", textBox37.Text);
com.Parameters.AddWithValue("#b", "Active");
con1.Open();
com.ExecuteNonQuery();
}
}
The correct syntax for an update statement is
UPDATE table SET field1=value1, field2=value2 WHERE field3=value3
You are using the wrong syntax hence the syntax error
As a side note, did you forget to use a parameter for the WHERE condition?
It is always correct to use a parameter for every value that you want to include in your query. Just remember to put it in the correct order because OleDb doesn't recognize the parameter by their name, but use a strictly positional order in the Parameters collection, so the first one goes assigned to the first parameter placeholder and so on.
easy way
using (var aq_pension = new System.Web.UI.WebControls.SqlDataSource())
{
aq_pension.ProviderName = "System.Data.OleDb";
aq_pension.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/stat_tresor/stat_tresor/stat_tresor/db/stat1.mdb";
aq_pension.UpdateCommand = "UPDATE tableaux1 SET nbre=0, montant_mois=0,total=0 WHERE code <>''";
aq_pension.Update();
}
I'm trying to write a program using SQL and OleDB and I get an error while the Program is running.
the program first counts the number of rows in the table(access table which called 'tblCodons')
and storage the number as integer in j.
then the program stores all the rows (from a specific column which called 'codonsFullName') in comboBox1.
the code is below
I get this ERROR:System.Data.OleDb.OleDbException (0x80040E14): Invalid SQL statement;Required values' DELETE ',' INSERT ',' PROCEDURE ',' SELECT 'or' UPDATE
the code:
int j=0;
OleDbConnection conn1 = new OleDbConnection(connectionString);
conn1.Open();
string sqlCount= "SET #j= SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons";
OleDbCommand counter = new OleDbCommand(sqlCount, conn1);
counter.ExecuteNonQuery();
conn1.Close();
OleDbConnection conn2 = new OleDbConnection(connectionString);
conn2.Open();
string sqlFill = "SELECT tblCodons.codonsFullName FROM tblCodons";
OleDbCommand fill = new OleDbCommand(sqlFill, conn2);
fill.ExecuteNonQuery();
OleDbDataReader dataReader = fill.ExecuteReader();
dataReader.Read();
for (int i = 0; i < j; i++)
{
comboBox1.Items.Add(dataReader.GetString(i));
}
You seem to need the count only for the loop. Also I do not understand why you are executing fill.ExecuteNonQuery() before executing is as a reader.
Also setting #j (if it did work) in a sql query has no scope to a local variable j in the code you are trying to set.
You should only need the following code (apologies for any syntax errors)
OleDbConnection conn2 = new OleDbConnection(connectionString);
conn2.Open();
string sqlFill = "SELECT tblCodons.codonsFullName FROM tblCodons";
OleDbCommand fill = new OleDbCommand(sqlFill, conn2);
OleDbDataReader dataReader = fill.ExecuteReader();
int j = 0;
if (dataReader.HasRows)
{
while(dataReader.Read())
{
comboBox1.Items.Add(dataReader.GetString(0));
j++;
}
}
Hope that helps
Leaving this answer here as an explanation for fixing your code as it currently exists, but also want to point out that I recommend going with Kamal's solution; it only queries the database once.
This line is probably your error:
string sqlCount= "SET #j= SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons";
change to
string sqlCount= "SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons";
You'll want to change your code to obtain the result of that first query like this:
j = counter.ExecuteScalar();
First, as Kamal Mentioned you can't directly set a variable from a sql query as you are trying to do and as the exception states only "SELECT" , "INSERT","UPDATE" and "DELETE" commands can be use in a query.
Second, I don't know why you need to get the record counts before getting the actual data but if it's really necessary you can write your query like this :
var query="SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons;SELECT tblCodons.codonsFullName FROM tblCodons;";
Then you can execute both query using a single DataReader. When you execute DataReader.ExequteQuery() it will contain two results.the first one has access to the count and the second one has access to actual data.
Here's an example