IDataReader not reading, no errors - c#

I realize IDataReader is outdated and some view it as dirty code, but on the site I am working on this is what they use. I have an IDataReader statement to run a query to get a specific id from a table using multiple joins. Now this site has a DAL but it only supports the ability to select from one table at a time, so using select statements with joins do not work with it. This is why I am forced to use IDataReader with this.
if (Request.QueryString["CategoryId"].ToString() == "0")
{
using (IDataReader getCategoryID = DB.GetRS("SELECT ItemCatalogCategory.CategoryID FROM UserCustomerCatalog INNER JOIN ItemCatalogCategory ON UserCustomerCatalog.ItemProfileCatalogID = ItemCatalogCategory.ItemProfileCatalogID " +
"INNER JOIN ItemCategory ON ItemCatalogCategory.CategoryID = ItemCategory.CategoryID INNER JOIN StoreCatalog ON UserCustomerCatalog.StoreCatalogID = StoreCatalog.StoreCatalogID " +
"WHERE UserCustomerCatalog.ItemProfileCatalogID = '" + Request.QueryString["CatalogID"] + "' AND UserCustomerCatalog.CustomerID =' " + Session["Customer"].ToString() + "' AND ItemCategory.ProductID = '" + productis + "'"))
{
if (getCategoryID.Read())
{
string categoryID = getCategoryID["ItemCatalogCategory.CategoryID"].ToString();
string lookmike = Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + categoryID;
Response.Redirect(Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + categoryID);
}
else
{
Response.Redirect(Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + Request.QueryString["CategoryId"]);
}
}//end using getCategoryID
}
this is what I have, but when it gets to:
if (getCategoryID.Read())
it renders as false, there are no exceptions thrown, and no errors or warnings. I have done this type of select in the past with no problems, but I cannot figure out why .Read() is returning false.
Can anyone suggest possible reasons for it not reading? If more code is needed, I can provide as needed. Any help is appreciated, thank you in advance.

Looking at your SQL text there is a little typo that could wreak havoc with the results
"WHERE UserCustomerCatalog.ItemProfileCatalogID = '" + Request.QueryString["CatalogID"] +
"' AND UserCustomerCatalog.CustomerID =' " + Session["Customer"].ToString() + "' AND ..... "
here ^
That space mangles your query and give no result.
Let me also repeat that you have a problem with SQL Injection as other members have already said. You could add an overload to your actual implementation of GetRS that receive also a SQLParameter collection to add to the command used to build your SqlDataReader. Something like this
public SqlDataReader GetRS(string sqlText, SqlParameter[] prm)
{
....
SqlCommand cmd = new SqlCommand(sqlText, conn);
cmd.Parameters.AddRange(prm);
.....
}
and then start to upate the calling code.

Related

AND statement in mySQL [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I'm trying to run a query in MySQL database with C#. I want the column prioritySettings returned when the 3 previous columns are within certain values. This query works, but only with one variable at a time, so at the moment I can only specify the value of one of the columns. Are my AND statements correct?
string query = "SELECT prioritySetting FROM {DATABASE} WHERE handling ='" + handling + "'" + "AND corner ='" + corner + "'" + "AND power ='" + power + "'";
some more code;
MySqlDataReader sqlReader;
string handling = overOrUnderInput;
string corner = cornerPartInput;
string power = onOrOffPowerInput;
string query = "SELECT prioritySetting FROM {DATABASE} WHERE handling ='" + handling + "'" + " AND corner ='" + corner + "'" + " AND power ='" + power + "'";
MySqlCommand getRecords = new MySqlCommand(query, connection);
connection.Open();
sqlReader = getRecords.ExecuteReader();
while (sqlReader.Read())
{
try
{
try
{
suggestions[i] = (sqlReader.GetString(0));
}
catch
{
}
i++;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
and the error;
System.NullReferenceException: Object reference was not set to an instance of an object.
Seem like a space is required before each AND.
Add a space before each AND
string query = "SELECT prioritySetting FROM {DATABASE} WHERE handling ='" + handling + "'" + " AND corner ='" + corner + "'" + " AND power ='" + power + "'";
Let's see how your query looks if the parameters are inserted. I assume parameters have values equal to their names.
SELECT prioritySetting
FROM {DATABASE}
WHERE handling ='handling'AND corner ='corner'AND power ='power'
If it's really DATABASE after the FROM you should change it to TABLE. I'm not very sure if it causes any problems, but I strongly recommend putting spaces before ANDs. So your code line will be like:
string query = "SELECT prioritySetting FROM {DATABASE.TABLE} WHERE handling ='" + handling + "'" + " AND corner ='" + corner + "'" + " AND power ='" + power + "'";
string query = "SELECT prioritySetting FROM {TABLE}
WHERE handling ='" + handling + "'" + "
AND corner ='" + corner + "'" + "
AND power ='" + power + "'";

multiple Parameters - Syntax error in string in query expression: VS 2010 with MS-Access 2003

I am receiving
OleDBException was unhandled error of "Syntax error (missing operator) in query
expression '(StudentID = 100' OR StudentName = 'Nick' OR StudentCNCI = '78894452)Bob'."
private void btnFind_Click(object sender, EventArgs e)
{
string title = textBox1.Text.ToString();
string queryString = "SELECT * FROM Students WHERE (StudentID = " + StudIDTb.Text.ToString() + "' OR StudentName = '" + StudNameTb.Text.ToString() + "' OR StudentCNCI = '" + StudCNCITb.Text.ToString() + ")" + title;
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Connection = myCon;
myCon.Open();
OleDbDataReader dr = command.ExecuteReader(); // error pointing here
while (dr.Read())
{
StudIDTb.Text += String.Format("StudentID: {0}\n", dr["StudentID"].ToString());
StudNameTb.Text += String.Format("StudentName: {0}\n", dr["StudentName"].ToString());
StudCNCITb.Text += String.Format("StudentCNIC: {0}\n", dr["StudentCNIC"].ToString());
StudDOBTb.Text += String.Format("StudentDOB: {0}\n", dr["StudentDOB"].ToString());
}
myCon.Close();
}
I have also tried...
string queryString = "SELECT * FROM Students WHERE (StudentID = " + StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text + "' OR StudentCNCI = '" + StudCNCITb.Text + ")" + title;
I don't want to give you wrong impression I am "lazy" but I am assuming I am getting this error because I have query it incorrectly or I have made a typo error or could it be something else. Please can someone help me, thanks in advance.
ps I know I am getting criticism for not using parameterized queries. I will change it once I got the basic right. I know a lot of similar questions have been asked here but I still can't get it right.
UPDATE 1
I have changed it to
"SELECT * FROM Students WHERE StudentID = " + StudIDTb.Text + " OR StudentName = '" + StudNameTb.Text + "', OR StudentCNCI = '" + StudCNCITb.Text + ")";
I am now receiving error of...
Syntax error (comma) in query expression
I am looking into it
Update 2
string queryString = "SELECT * FROM Students WHERE StudentID = " + StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text + "' OR StudentCNCI = '" + StudCNCITb.Text + "'";
Receiving the same error.
Looking into it
Update 3
If it can't be solved I do it the way it should be, using parameterized queries as highly recommended if it means to solve the problem and probably easy to spot any problems with the code
It's telling you that your query is invalid. You have this
SELECT *
FROM Students
WHERE (StudentID='a' OR StudentName='b' or StudentCNCI='c')Bob
It's not liking that Bob on the end and it's not clear why you need it. Explain what your intent is there, or just get rid of it as it doesn't appear to be necessary for your query.
string queryString = "SELECT * FROM Students WHERE StudentID = '" +
StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text +
"' OR StudentCNCI = '" + StudCNCITb.Text + "'";
As you mention in your post, you need to parameterize your query also. Let us know if you need help with that, but it is pretty straightforward, and a common post on here, so you already have plenty of resources to figure that out.
EDIT: If you like, you can remove the parenthesis. You'd really only need then if you were going to do a subquery or some such thing. They won't hurt your query, they're just not really necessary.
SELECT *
FROM Students
WHERE StudentID='a' OR StudentName='b' or StudentCNCI='c'
Also, from other comments, you actually have multiple quote mismatches (one at the beginning and another at the end).

Read Data from data set

I have data set that is being filled from sql query, like this
cmd_sql.CommandText = " SELECT BrDok " +
" FROM ordersstavke " +
" WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'";
MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet ds_dok = new DataSet("ordersstavke");
sql_adapter.Fill(ds_dok);
Now I want to extract value from data set for sql update, like this one
myQuery = "UPDATE ordersstavke " +
"SET BrDok = '" + rw_mat["brdok"] + "', " +
"SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
"WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] + "'";
I tried this ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] but I got an error,
I was thinking to do something like this
string BrDok;
BrDok = ds_dok.["BrDok"].ToString();
But nothing, how to extract that BrDok or just put it into procedure?
Thanks infront!
Make it
DataSet ds_dok = new DataSet("ordersstavke");
sql_adapter.Fill(ds_dok,"BrDok");
Then use
ds_dok.Tables["BrDok"].Rows[0]["BrDok"].ToString()
Try this
ds_dok.Tables[0].Rows[0]["BrDok"]
If you provide a string argument for the dataset class, then it will be the dataset name and not the datatable name. And there is no table in the database with name you provided for a dataset, so give it while filling the dataset. Write some thing like below.
DataSet ds_dok = new DataSet();
sql_adapter.Fill(ds_dok,"ordersstavke");
and you can write all the remaining code as it is in your code part.
And your second update query has some syntax error, see it like below
myQuery = "UPDATE ordersstavke " + "SET BrDok = '" + rw_mat["brdok"] + "', "
+ "SifParFil = '" + rw_mat["sifskl_kor"] + "', " + "WHERE BrDok
= '" + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] + "'";
You forgot to put an starting inverted comma at the where clause.
Just a small hint to the sql-command. You should use sql-parameters to prefent sql-injection.

Update/Insert into table

I have to update table on SQL Server but first i have to check for existing data in table so if data is there update it, if not make a new insert:
cmd_sql.CommandText = " SELECT BrDok as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'" +
" AND DokumentTip = '" + rw_mat["vrst_dok"] + "'";
MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
sql_adapter.Fill(dt_dok);
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, DocumentTip, SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["vrst_dok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else
{
UPDATE DATA
}
But I have an error in the code, the error is here if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
Object reference not set to an instance of an object.
The problem is in this if statement...
DOK_MAT_EXCHANGE is the name of the DataSet, not of the first table.
You should test with
if (dt_dok.Tables[0].Rows.Count == 0)
Also, I think is better to use a syntax like this to discover how many records are presents
cmd_sql.CommandText = "SELECT COUNT(BrDok) as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = ?p1 " +
" AND DokumentTip = ?p2";
cmd_sql.Parameters.AddWithValue("?p1", rw_mat["sifskl_kor"] );
cmd_sql.Parameters.AddWithValue("?p2", rw_mat["vrst_dok"] );
int rowCount = (Int32)cmd_sql.ExecuteScalar();
change
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
to
DataSet dt_dok = new DataSet("ordersstavke ");
and
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
to
if (dt_dok.Tables["ordersstavke "].Rows.Count == 0)
Accessing the first table via the dataset name is incorrect, that's for setting the XML.
Instead use
dt_dok.Tables[0].Rows.Count;
That being said, you're better off writing this as a single SQL statement instead of a separate select && insert. This way you're not going to the DB multiple times.
var sql = #"if exists(select * from ordersstavke where SifParFil = ? and DokumentTip = ?)
then
-- do insert statement
else
-- do update
end if";
This might also be better done with a stored proc, so you don't have as much SQL code in C#. It's easier to manage multiple operations that way.
And for crying out loud, use SqlParameters, not string concatenation! That's just asking for trouble!
Ok, thanks guys, I wrote it like this
if (ds_dok.Tables[0].Rows.Count <= 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else if (ds_dok.Tables[0].Rows.Count >= 1)
{
myQuery = "UPDATE ordersstavke " +
"SET BrDok = '" + rw_mat["brdok"] + "', " +
"SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
"WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString() + "'";
}
But there is a small problem in the section update: s_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString(), here it give me that loving error : Object reference not set to an instance of an object.
Maybe the update on MySQL goes on different way, I'm referencing on example on sql server and there update goes differently

MySQL Returning Column Names instead of their Content

Okay, so in the past few weeks I've probably written about 40 select statements. So, I know how to do it. And I've just written another one, but this time I need to use ComboBox values to match against, and it keeps resulting in the names of the column (the right column, mind you), instead of what's inside the column.
string st = "SELECT '" + txtchange.Text + "'
FROM mysql_9269_dbase." + pages.Text + "";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
cd.CommandType = CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while(msdr.Read())
{
txt.Text = msdr[0].ToString();
}
Now, why is it returning the column name instead of the content of that column?
Lose the single quotes.
Change
"SELECT '" + txtchange.Text + "' "
to
"SELECT " + txtchange.Text + " "
In sql you can do it like this.
string query = "Execute("+"'SELECT " + txtchange.Text + " FROM mysql_9269_dbase." + pages.Text + "')";

Categories

Resources