OdbcException was caught while firing the SQL query - c#

'admin_table_name' is string array containing the names of table which are taken as an input from text file and 'table_index' is the index of an array.so,while firing the query below,"admin_table_name[table_index]" is avoided by throwing 'OdbcException was caught' as an exception.what is the mistake i am making in the code? please help.
cmd.CommandText = "SHOW KEYS FROM " + admin_table_name[table_index] + " where Key_name = 'PRIMARY'";
dr = cmd.ExecuteReader();

Why use ODBC? For most databases are native Drivers available.
Can you post the the complete String of the CommandText before executing the Reader?

Related

SQL query not working properly in C# while a lot of data is applied one by one

I have a problem while reading from SQL Server in C#. It is happening in SSIS, I have inserted a C# script in data flow.
I am using the code below:
using (SqlConnection connection = new SqlConnection(connectionString))
{
string vendorName = Row.VendorName.ToString().Substring(0,1).ToUpper() + Row.VendorName.ToString().Substring(1);
using (SqlCommand command = new SqlCommand("Select TOP 1 * from Logs where MessageId = '" + Row.id.ToString() + "'" +
"AND name = (Select Id from Names where vendor_name = '" + vendorName +
"order by CreatedDate desc", connection))
{
connection.Open();
string status = "";
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
status = oReader["Status"].ToString();
}
}
if (String.IsNullOrEmpty(status))
{
SaveDataToDB(Row.id, Row.VendorName, "Unknown");
}
}
}
In the Logs table, there are about 10000 rows, and the related datasource, where Row data belongs to, has around 9000 records. The problem is that, even though the query is working well, in the script it sometimes brings status value as null, because it cannot find the record in the SQL. I am getting the query and copy/pasting it to SQL, executing the query brings result there, but not in C# somehow. For example, I am running the C# two times in sequence, at the first time it says Status is null for the id: 354456, but when I run it at the second time it finds 354456 correctly but saying that status of 354499 is null.
Any idea for me to solve this issue? I really appreciate for any help.
According to me, this could be due to order of evaluation of user defined values embedded within the query. Could be the first dynamic value might be evaluated before the one in the inner query.
As I am not sure about the value to variable binding, however, I would recommend you to check following points;
a) externalise both your variable (vendor name and row id) outside and evaluate and ensure it has respective values
b) and then form your query statement with the evaluated values
May be you can debug and see the CommandText of command object just before call Execute.
your code is really inefficient, you should cache vendorname in a string and do all the substring operations on that.
for example:
string vendorName = Convert.ToString(Row.VendorName);
vendorName = vendorName.Substring(0,1).ToUpper() + vendorName.Substring(1);
instead of selecting all the columns, select the specific column for a speed up select Status from.
try to debug your code first, see which id you are getting and what is the result of your query.
its really hard to debug your code without any debug information.
change your code to this (Select Id from Names where vendor_name = '" + vendorName + "')" and put a blank space next to every " character e.g. " AND instead of "AND

Append DataReader Results to QueryDef.SQL

If I use OleDb to connect to a database then use this to capture the info into a datareader -- how could I append this datareader results to a separate query that I am building?
string appendSQL = "";
xxx = new OleDbCommand("Select * from tbl_local, connstring);
dr = xxx.ExecuteReader();
while (dr.Read())
{
appendSQL = dr["salestatus"].ToString() + ",";
}
---- Separate Query I am building that I want to append the datareader results to:
var qd = new DAO.QueryDef();
qd.SQL = String.Format("Select salesName, saleAmount" + appendSQL + "dateSold from saleDB");
The above shows what I want to do, but when I try that I get multiple errors :(
That syntax as far as a coding standpoint goes looks good. Check your SQL statement and verify there are no issues with your SQL statement. Another solution would be to post the actual errors you are receiving as that will help us narrow down exactly what is causing the issue. As far as the syntax for joining multiple strings together in C# it is below. That would join the values of all three.
qd.SQL = String.Format(appendSQL + appendSQL1 + appendSQL2);

Saving an image in an Informix database using C# code?

How do I save an image in an Informix database using C# code?
At the moment, I'm unable to save an image in an Informix database using C# code.
All the steps work, only when the query is about to get executed it throws error "E42000: (-201) A syntax error has occurred."
Below is the code.
mycon.Open();
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
HttpPostedFile img = Upload.PostedFile;
Response.Write("Size of file = " + pic);
img.InputStream.Read(pic, 0, len);
//Upload.PostedFile.InputStream.Read(pic,0,len);
string str = "insert into imageinfo (name,address,photo) values('" + txtname.Text + "','" + txtaddress.Text + "'," + pic + ")";//,photo,#photo
mycmd = new OleDbCommand(str, mycon);
//mycmd.Parameters.AddWithValue("#id", int.Parse(txtid.Text));
mycmd.Parameters.AddWithValue("#name", txtname.Text);
mycmd.Parameters.AddWithValue("#address", txtaddress.Text);
mycmd.Parameters.AddWithValue("#photo", pic);
mycmd.ExecuteNonQuery();
mycon.Close();
lblMessage.Text = "Image details inserted successfully";
Response.Redirect("~/RetriveImage.aspx");
mycon.Close();
It starts with your code being a copy/paste mess from at least 2 sources because it makes no sense.
Your insert has the values directly - and you can not put pic in like that, sorry - but you define parameters that are not used. 2 sources code.
Then the code was mindlessly copy/pasted. You define named paraameters, but OleDb does not support named parameters (http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/thread/637db5d4-e205-489c-b127-7ca14abc48e3/) only parameter by position, which tells me you enver ever used parameters with Informix via OleDb and just copied/pasted the code together.
Remove the direct data in the INSERT statement, put in parameter markers.
Then use the parameters, as per the MS link I sent you (positional, marker is a ?).
Then it will work.
Occasionally it may require you to actually read the documentation instead of just stitching together code from different sources and asking for help.

SQL Syntax Error only in C# code

I have this code:
"SELECT tblschemeprojectpaymentgateway.paymentgatewayid, paymentgatewayname FROM " +
"tblschemeprojectpaymentgateway INNER JOIN tblpaymentgateway ON " +
"tblschemeprojectpaymentgateway.paymentgatewayid = tblpaymentgateway.paymentgatewayid"+
"WHERE tblschemeprojectpaymentgateway.schemeprojectid=`"+
SchemeProjectID.ToString()+"`", SqlConnection1);
sqlcmd.CommandType = CommandType.Text;
SqlConnection1.Open();
Npgsql.NpgsqlDataReader dr = sqlcmd.ExecuteReader();
which queries a Postgresql database. SchemeProjectID is a Guid. This code executes fine with the pgAdmin database query tool, but throws a syntax error in the C# code soemwhere around "tblschemeprojectpaymentgateway".
I have tried the SchemeProjectID in quotes, backtics and just as it is - with and without the .ToString().
I can not figure out what is wrong.
Classic problem when splitting strings over several lines; you're missing the space between tblpaymentgateway.paymentgatewayid and WHERE.
To help avoid missing spaces in strings split over multiple lines, I have found it helpful to use the # symbol before the string to take a multi line string literally. Like such:
string command = #"SELECT tblschemeprojectpaymentgateway.paymentgatewayid, paymentgatewayname FROM
tblschemeprojectpaymentgateway INNER JOIN tblpaymentgateway ON
tblschemeprojectpaymentgateway.paymentgatewayid = tblpaymentgateway.paymentgatewayid
WHERE tblschemeprojectpaymentgateway.schemeprojectid=`" + SchemeProjectID.ToString() + "`";
Also, you may want to look into parameterizing your statements and possibly wrapping them in stored procedures.
You are missing a space on the third line before the WHERE.
"SELECT tblschemeprojectpaymentgateway.paymentgatewayid, paymentgatewayname FROM " +
"tblschemeprojectpaymentgateway INNER JOIN tblpaymentgateway ON " +
"tblschemeprojectpaymentgateway.paymentgatewayid = tblpaymentgateway.paymentgatewayid "+
"WHERE tblschemeprojectpaymentgateway.schemeprojectid=`"+

Updating SQL column based on text file (foreach line in it)

What I have is an extremely large text file that needs to go into a specific column at a specific raw. The file is around 100k lines. So what I want to do is read the whole file, and for each line append into that specific SQL column the line. Here's what I have but i really need help on the SQL query
string[] primaryfix = File.ReadAllLines(dinfo+"\\"+filex);
string filename = filex.ToString();
string[] spltifilename = filename.Split('.');
foreach (string primary in primaryfix)
{
string sqltable = ("dbo.amu_Textloadingarea");
string sql = "update " + sqltable + " set [Text] = [Text] + '" + primary + "' where begbates = '" + spltifilename[0] + "'";
SqlConnection con = new SqlConnection("Data Source= Corvette ;Initial Catalog= GSK_Avandia_SSECASE;Integrated Security= SSPI");
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
con.Close();
}
everything is fine except for the string sql, it doesn't update the way I would like it to.
Any help is always appreciated.
Look likes you're trying to read from the database with that code inside the loop. SqlDataReader provides a way to read rows from the database, but not the other way around.
Replace
SqlDataReader reader = cmd.ExecuteReader();
with
cmd.ExecuteNonQuery();
The first thing I see is that you are not escaping the input from the text file; any SQL escape characters (like a single quote) will break that command. I'd recommend using parameters so you needn't worry about escapes at all.
Other than that, nothing pops to mind that would suggest why the command isn't working, but I do wonder if it might not cause fewer problems if it's such a large file to read it line-by-line rather than all at once.

Categories

Resources