I am using an Informix db, and I am trying to get data for a specific item and store it in a datatable.
I checked the following:
1) connection string looks good
2) the connection is able to open
3) I used the same connection string from the web.config on a dataset creating a table adapter and it is able to retrieve the record.
This is the code I am using:
var connectionstring = ConfigurationManager.ConnectionStrings["TestDataTable"].ConnectionString;
OdbcConnection con = new OdbcConnection(connectionstring);
//con.ConnectionString = connectionstring;
if (TxtItem.Text != hold_item)
{
con.Open();
OdbcCommand cmd = new OdbcCommand(#"Select t_item,t_idsc,t_upct,
t_item_upc,t_ctyp,t_citg,
t_best,t_disp,t_mold,t_csel
from informix.tsckcm907
where t_item = " + stitem, con);
OdbcDataReader myReader = cmd.ExecuteReader();
DataTable testdt = new DataTable();
testdt.Load(myReader);
foreach (DataRow row in testdt.Rows)
{
lbldesc.Text = row["t_idsc"].ToString();
Spanish_Item();
{
DropDownList2.SelectedIndex = 1;
object stlanguage = 1;
hold_language = Convert.ToString(stlanguage);
TxtBestBefore.Text = row["t_best"].ToString();
holdbest = Convert.ToInt16(TxtBestBefore.Text);
}
}
myReader.Close();
myReader.Dispose();
cmd.Dispose();
con.Close();
con.Dispose();
}
in debug mode my error occurs at the OdbcDataReader line:
error message:
An exception of type 'System.Data.Odbc.OdbcException'
occurred in System.Data.dll but was not handled in user code
Additional information: ERROR [42000] [Informix]
[Informix ODBC Driver][Informix]A syntax error has
occurred.
If your Informix ODBC driver says: "A syntax error has occurred" then you have to check your SQL statement:
"Select t_item,... from informix.tsckcm907 where t_item = " + stitem
I think that something is wrong with stitem. We don't know what type and value it is, but if its type is some kind of string or date then it may be in the wrong form. Easiest way is to extract full SQL statement (simply print it before execution) and use it with some database editor (for example db_access from Informix). Then make it work in SQL editor and transform stitem variable into acceptable form (add quotes, escape internal quotes, escape special characters etc.)
I also recommend use of PreparedStatement that separates your query from data. This way you do not need to worry about stitem form. No quotes, no escaping, just place holder in query string and value added separately.
I don't use C# but I see that C# can work with preapred statements with unnamed parameters:
cmd.CommandText = "SELECT ... FROM ... WHERE t_item = ?";
cmd.Parameters.Add("#t_item", ObdcType.VarChar, 200).Value = t_item;
or with named parameters:
cmd.CommandText = "SELECT ... FROM ... WHERE t_item = #t_item";
cmd.Parameters.Add("#t_item", ObdcType.VarChar, 200).Value = t_item;
I use unnamed parameters from ODBC so Informix driver can work with such parameters but you will have to check it yourself with C#.
Related
After I try to output the password in the dataGrid, from the given Username in the txt_Username textbox, I get this error message:
MySql.Data.MySqlClient.MySqlException: "Unknown column 'Test' in 'where clause'"
MySqlDataAdapter da = new MySqlDataAdapter("Select Password from tbl_anmeldedaten Where Username=" + txt_Username.Text, con);
da.SelectCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
The exact cause of the error is that you are trying to execute the following query:
SELECT Password
FROM tbl_anmeldedaten
WHERE Username = Test;
Does it look like Test should have single quotes around it? Yes, it should, and you could add that to your raw query. But, concatenating a query like this in C# leaves open the possibility for SQL injection. A much better approach is to use prepared statements:
string sql = "SELECT Password FROM tbl_anmeldedaten WHERE Username = #val1";
MySqlCommand cmd = new MySqlCommand(sql, MySqlConn.conn);
cmd.Parameters.AddWithValue("#val1", txt_Username.Text);
cmd.Prepare();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// consume a record in the result set
}
You are using string concatenation which is a vector for SQL injection attacks. Perhaps the username in the text field is doing some SQL which it shouldn't be allowed to (for instance '' OR Test=1. There are plenty of resources on using parameterized queries which should remedy the problem.
I am accessing an Oracle database in my asp.net application, and am getting this error:
ORA-00936: missing expression
My c# code is:
getInfoByPoNum =
"SELECT h.SYS_HEADER_ID,
h.FOLIO1 AS INV_NUMBER,
v.VENDOR_NAME,
CASE WHEN h.Comments LIKE '%CLOSED%' THEN 'CLOSED' ELSE NVL(h.Comments, 'OPEN') END AS CComments,
h.ORG_ID
FROM INV_HEADERS h, VENDORS v
WHERE h.LOOKUP_CODE in ('STANDARD', 'BLANKET')
AND h.VENDOR_ID = v.VENDOR_ID
AND h.FOLIO1 = #invNumber"
OracleCommand CMD = new OracleCommand();
OracleConnection CONN = new OracleConnection(constring.ConnectionString);
CMD.Connection = CONN;
CONN.Open();
CMD.Parameters.Clear();
CMD.Parameters.Add(new OracleParameter("#invNumber", INVNumber));
CMD.CommandText = getInfoByPoNum;
using (var reader = CMD.ExecuteReader())
{
while (reader.Read())
{
The error occurs at CMD.ExecuteReader().
Based on other posts on SO and on the web, the query is correct and runs in oracle sql-developer.
What is causing the syntax error?
Update: If I modify the oracle query and enter a valid invoice number value instead of #invNumber, the query executes fine in my application.
getInfoByPoNum =
"SELECT h.SYS_HEADER_ID,
h.FOLIO1 AS INV_NUMBER,
v.VENDOR_NAME,
CASE WHEN h.Comments LIKE '%CLOSED%' THEN 'CLOSED' ELSE NVL(h.Comments, 'OPEN') END AS CComments,
h.ORG_ID
FROM INV_HEADERS h, VENDORS v
WHERE h.LOOKUP_CODE in ('STANDARD', 'BLANKET')
AND h.VENDOR_ID = v.VENDOR_ID
AND h.FOLIO1 = 2241QSA"
I believe that for Oracle your parameter should be specified as :invNumber, not #invNumber in your query:
AND h.FOLIO1 = :invNumber"
And when setting your parameter, it should look like this (just remove the #):
CMD.Parameters.Add(new OracleParameter("invNumber", INVNumber));
EDIT
You may also need to enable parameter binding by name (I think it's positional by default):
CMD.BindByName = true;
Try putting all your query in the same line, it seems that only the first line of the string is being executed. Also check if there isnĀ“t any escape character or special character that you have to treat with a "\" character.
And this may also occur, in my experience, when attempting to execute SQL with a terminating semicolon in the Oracle managed driver for .NET/C#.
So in that situation, execute the SQL within a wrapper for consistency and
do not use
SELECT * FROM X;
use
SELECT * FROM X
in other words, strip it off.
Why aren't my parameterized variables being added to my Sql query?
I have two parametrized variables set by combobox.text which is selected by the end user.
I get the error below when trying to use a query that uses a parameterized variable.
Additional information: Must declare the scalar variable "#username"
Am I missing something?
Example Query
SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = #username and status = #status";
Code Snippet
//Decide what query
String SQL = SQLSelection();
//Connection String
String ConnString = "Data Source=dbsqlexpress; Provider=SQLOLEDB; Initial Catalog=Data; User ID=mobile; Password=PW";
//Create and initalize Oledbconnection object and pass connection string into it.
OleDbConnection con = new OleDbConnection(ConnString);
//open connection to database
con.Open();
//create adapter that sits inbetween dataset and datbase
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(SQL,con);
adapter.SelectCommand.Parameters.Add("#username", OleDbType.VarChar).Value = auditorCmb.Text;
adapter.SelectCommand.Parameters.Add("#status", OleDbType.VarChar).Value = statusCmb.Text;
//Create dataset
DataSet dataset = new DataSet();
using (DataTable dt = new DataTable())
{
adapter.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
dataGridView1.DataSource = dt;
int rowCount = rowCount = dt.Rows.Count;
label10.Text = rowCount.ToString("n0");
}
}
With OLE DB (and ODBC), you need to specify ? as parameter markers in the SQL statement. These are then mapped by ordinal according to the order parameters were mapped to the collection.
SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = ? and status = ?;";
Avoid using OLE DB and ODBC in .NET applications. The .Net Provider for SQL Server (a.k.a SqlClient) will provide better performance from .Net Applications. Also, Microsoft has announced deprecation of OLE DB for relational database access in SQL Server.
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
MSDN:OleDbCommand.Parameters Property
I am using Microsoft Access to create a "Desktop Database" and saved it as "new.mdb" into my C# Debug folder.
However, upon using the SELECT statement, my C# project throws an Exception.
This is my database
And this is my code
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=new.mdb");
conn.Open();
dataset = new DataSet();
string sqlStatement = "SELECT * FROM User";
dbAdapter = new OleDbDataAdapter(sqlStatement, conn);
oOrderDetailsCmdBuilder = new OleDbCommandBuilder(dbAdapter);
dbAdapter.Fill(dataset);
contactsTab = dataset.Tables[0];
contactsTab.TableName = "User";
rows = contactsTab.Rows;
The error upon executing that code is
Syntax error in FROM clause.
However, the query looks fine. Is there anything wrong?
Thanks!
EDIT :
OleDbCommand.ExecuteNonQuery (Example : Creating new table) works for this. I'm not sure why SELECT statement doesn't :/
User is a reserved keyword in SQL. So write SQL like below
string sqlStatement = "SELECT * FROM [User]";
I have a problem trying to parameterize some "dynamic" SQL build in an existing C# class used by an ASP app. The environment is:
Win Server 2008
.NET 3.0
C#
DB2 9.x ([IBM][CLI Driver][DB2])
The existing code just concatenates the SQL with the param strings in a long SQL string - which is of course at risk for SQL injection. As is my practice whenever I see this, I tend to change the code to use parameters. But with this code I am failing. I have tried "#" and I have tried "?" - the latter is what I understand to be necessary for ODBC.
Here is a simplified code snippet (forgive me if I don't format it right - this is my first question) that I have compiled and run:
private DataSet test(String schemaName )
{
String sortField = "TABLE_NAME.COLUMN_NAME";
String sortDirection = "ASC";
OdbcConnection conn = new OdbcConnection();
DataSet ds = new DataSet();
string connStr = ConfigurationManager.AppSettings[schemaName] + dbUser;
try
{
conn.ConnectionString = connStr;
OdbcCommand cmd = new OdbcCommand("SELECT * FROM TABLE_NAME ORDER BY ? ? ");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(sortField);
cmd.Parameters.Add(sortDirection);
logger.log("cmd SQL = \t" + cmd.CommandText );
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ex.Data.Add("Location:", "test()");
ex.Data.Add("Connection", conn.ConnectionString);
logger.logException(ex);
throw ex;
}
finally
{
conn.Close();
}
}
Log printout:
cmd SQL = SELECT * FROM TABLE_NAME ORDER BY ? ?
Where TABLE_NAME is of course the table I am querying.
What I get in return is this (some proprietary info removed:
EXCEPTION occured at 4/26/2012 12:29:41 PM ERROR [42601] [IBM][CLI
Driver][DB2] SQL0104N An unexpected token "?" was found following "".
Expected tokens may include: "MICROSECONDS MICROSECOND SECONDS SECOND
MINUTES MINUTE HOURS". SQLSTATE=42601
at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)Connection Driver={IBM DB2 ODBC DRIVER};
.....
Changing this to a stored proc is not allowed.
Upgrading to a later version of .NET is not allowed.
Changing/upgrading the ODBC driver is not allowed.
What I am seeing indicates to me that the "?" parameter is not being replaced.
I have tried AddWithValue() and I have tried Add(OdbcType.VarChar).Value = sortField (or something to that effect).
I am kind of at my whit's end - all of the googling and searching here indicates to me that the code above should work, but so far I have not been able to get the parameters in the SQL substituted with the variables.
Thanks in advance.
The reason the ? is an unexpected token is because you are using it in the ORDER BY clause (which I don't think is allowed).
The reason to use parameters is to mitigate the risks of user input. When building your query, if the ORDER BY field and direction are not coming via user input, you are safe in building the query with concatenation.
Only use the ? in the WHERE clause:
OdbcCommand cmd = new OdbcCommand("SELECT * FROM TABLE_NAME WHERE ID = ? ORDER BY " + sortField + " " + sortDirection);