SqlDataReader not reading any row apart from first - c#

New to stackoverflow and very much a c# beginner
Currently creating a form which produces a bar chart from data stored in a database. The chosen record is identified by pID (patient's ID) and tdate (Test date). These values are determined by 2 combo boxes that the user can select from, The problem I am having is that only the first and last records stored in the database are populating the barchart.
if (radioButtonTestResult.Checked)
{
foreach (var series in TestResultBarChart.Series)
{
series.Points.Clear();
}
string tdate = comboBox2.Text;
using (SqlConnection connection = new SqlConnection(#"Data Source= (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MMSEDB.mdf;Integrated Security=True"))
{
connection.Open();
string sql = "SELECT T_CLOCK_SCORE,T_LANGUAGE_SCORE,T_RECALL_SCORE,T_REGISTRATION_SCORE,T_ORIENTATION _SCORE,T_TIME FROM TEST_RESULTS WHERE P_ID='" + pID + "' AND T_DATE='"+ tdate +"'";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandTimeout = 3600;
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
MessageBox.Show("hello4");
String clockScoreString = reader["T_CLOCK_SCORE"].ToString();
MessageBox.Show(clockScoreString);
clockScore = Int32.Parse(clockScoreString);
String langScoreString = reader["T_LANGUAGE_SCORE"].ToString();
langScore = Int32.Parse(langScoreString);
String recallScoreString = reader["T_RECALL_SCORE"].ToString();
recallScore = Int32.Parse(recallScoreString);
String regScoreString = reader["T_REGISTRATION_SCORE"].ToString();
regScore = Int32.Parse(regScoreString);
String orientScoreString = reader["T_ORIENTATION_SCORE"].ToString();
orientScore = Int32.Parse(orientScoreString);
String timeScoreString = reader["T_TIME"].ToString();
timeScore = Int32.Parse(timeScoreString);
}
reader.Close();
}
}
this.TestResultBarChart.Series["Series1"].Points.AddXY("Clock Score", clockScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Language Score", langScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Recall Score", recallScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Registration Score", regScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Orientation Score", orientScore);
}
}
Here is a pic of the data:
Test_results_table
here is a pic of the interface with the first record working:
interface
I know this has something to do with the reader but can't work out how to get to function correctly
Any help is very much appreciated

You are reading in a loop all the returned values, then exit from the loop and use just the last value to set your Points. You should move the Point settings inside the loop
....
while (reader.Read())
{
clockScore = Convert.ToInt32(reader["T_CLOCK_SCORE"]);
langScore = Convert.ToInt32(reader["T_LANGUAGE_SCORE"]);
recallScore = Convert.ToInt32(reader["T_RECALL_SCORE"]);
regScore = Convert.ToInt32(reader["T_REGISTRATION_SCORE"]);
orientScore = Convert.ToInt32(reader["T_ORIENTATION_SCORE"]);
timeScore = Convert.ToInt32(reader["T_TIME"]);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Clock Score", clockScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Language Score", langScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Recall Score", recallScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Registration Score", regScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Orientation Score", orientScore);
}
reader.Close();
Note that your query is built using string concatenation. This is a well known problem with database code. Never do it and use a parameterized query
EDIT
Looking at your comment below, I repeat the advice to use a parameterized query instead of string concatenation. Not only this avoid Sql Injection hacks but also you don't leave the job to understand the meaning of your values to the database engine
DateTime tDate = Convert.ToDateTime(comboBox2.Text);
......
string sql = #"SELECT
T_CLOCK_SCORE,T_LANGUAGE_SCORE,T_RECALL_SCORE,
T_REGISTRATION_SCORE,T_ORIENTATION_SCORE,T_TIME
FROM TEST_RESULTS
WHERE P_ID=#id AND T_DATE=#date";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#id", SqlDbType.Int).Value = pID;
command.Parameters.Add("#date", SqlDbType.Date).Value = tdate;
command.CommandTimeout = 3600;
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
....
In this example I assume that the variable pID is of type integer and the variable tDate is of type DateTime matching the type of the database fields. This doesn't leave any doubt to the database engine on your values.
Of course if the fields are of different type then you should change the SqlDbType accordingly.

Related

Update Set command works in Access but not in Visual Studio with #parameters

I have been working on a personal project for the company I work for to control stock levels in order to practice my c#.
I want my application to search through tblJuiceStock, find a matching FlavourID to what the user is inputting and update the stock of that record through an UPDATE SET query.
public void InsertJuiceStockWithCheck()
{
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
string tblJuiceStockCheck = "SELECT FlavourID, Quantity FROM tblJuiceStock";
OleDbCommand cmdCheck = new OleDbCommand(tblJuiceStockCheck, conn);
OleDbDataAdapter daCheck = new OleDbDataAdapter(cmdCheck);
DataTable dtCheck = new DataTable();
daCheck.Fill(dtCheck);
foreach (DataRow row in dtCheck.Rows)
{
if ((int)row["FlavourID"] == fID)
{
int currentQty = (int)row["Quantity"];
int updatedQty = currentQty + qty;
string tblJuiceStockExisting = #"UPDATE tblJuiceStock
SET Quantity = #newquantity
WHERE FlavourID = #flavourID";
OleDbCommand cmdJuiceStockExisting = new OleDbCommand(tblJuiceStockExisting, conn);
cmdJuiceStockExisting.Parameters.AddWithValue("#flavourID", fID);
cmdJuiceStockExisting.Parameters.AddWithValue("#newquantity", updatedQty);
cmdJuiceStockExisting.ExecuteNonQuery();
matchFound = true;
break;
}
}
if (!matchFound)
{
string tblJuiceStockNew = "INSERT INTO tblJuiceStock (FlavourID, Quantity, MinStockPOS) VALUES (#fID, #quantity, #minstock)";
OleDbCommand cmdJuiceStockNew = new OleDbCommand(tblJuiceStockNew, conn);
cmdJuiceStockNew.Parameters.AddWithValue("#fID", fID);
cmdJuiceStockNew.Parameters.AddWithValue("#quantity", qty);
cmdJuiceStockNew.Parameters.AddWithValue("#minstock", amt);
cmdJuiceStockNew.ExecuteNonQuery();
}
}
}
Please note: this query works fine in Access when I replace parameters with the same values. Also, using breakpoints I identified that the parameters have the correct values set to them, the variables assigned to them are obtained within another method, all methods are called in the submit button event.
However, the Quantity value in TblJuiceStock remains the same.
My tblJuiceStock table
After some time of messing about the answer was simple.
OLEDB does work with named parameters but you have to declare them, if you don't declare them they use the parameters positioning to match them up.
My problem was that in my query string I had #newquantity first and #flavourID second, whereas when adding my parameters I added #flavourID first and #newquantity second.

Specifies that I have problems with my conn.open and my Conn.Close

this is how I select some content twice and when I get into the middle to select so like that it gives me trouble to select something on file.
The problem I have never seen before,
I think it's something with conn.open() and Conn.Close()
my code looks like this:
int prisId = Convert.ToInt32(Request.QueryString["Id"]);
cmd.Parameters.AddWithValue("#ppId", prisId);
cmd.CommandText = "SELECT priser FROM Priser WHERE Id = #ppId;";
conn.Open();
SqlDataReader readerPriser = cmd.ExecuteReader();
if (readerPriser.Read())
{
PanelerrorHandelsbetingelser.Visible = false;
string Brugerid = Session["id"].ToString();
cmd.Parameters.AddWithValue("#brugerid", Brugerid);
cmd.CommandText = "SELECT id, brugernavn, fornavn, efternavn FROM brugere WHERE Id = #brugerid;";
SqlDataReader readerBrugerid = cmd.ExecuteReader();
if (readerPriser.Read())
{
Session["id"] = readerBrugerid["id"].ToString();
Session["brugernavn"] = readerBrugerid["brugernavn"].ToString();
Session["fornavn"] = readerBrugerid["fornavn"].ToString();
Session["efternavn"] = readerBrugerid["efternavn"].ToString();
Session["adresse"] = TextBoxAdresse.Text;
Session["post"] = TextBoxPost.Text;
Session["telefon"] = TextBoxTelefon.Text;
Session["prisen"] = readerPriser["priser"].ToString();
LabelErrorBuyNow.Text = " - Yeaaa Jesper!";
}
else
{
LabelErrorBuyNow.Text = " - Der findes intet med dit brugerid!";
}
}
conn.Close();
problems come after line 9-10
The problem is such that it appears this one mistake on my part: There is already an open DataReader associated with this Command which must be closed first.
Always remember to release resources after they are used. So at the method end, you should:
cmd.Parameters.Clear();
readerPriser.Close();
conn.Close();
The exception tells you exactly what is wrong.
You have tried to run two SqlDataReaders over the same connection without either specifying MultipleActiveResultSets=True in your connection string or else first closing the first reader.
You have three options:
Use a second connection to run the second SqlDataReader.
Add "MultipleActiveResultSets=True" to your connection string.
Close the first SqlDataReader before using the second.
You need to close the readerPriser first be
readerPriser.Close();
Then affiliate the same command with next reader.
Always close the readers after using them.
There are two problems here. First of all, you are not placing all of your IDisposable objects into using blocks. Second, you are reusing the same SqlCommand for different queries. Third, your second Read call is using the wrong SqlDataReader.
Try
using (SqlConnection conn = new SqlConnection(...)){
conn.Open();
using (SqlCommand selectPriser = new SqlCommand("SELECT priser FROM Priser WHERE Id = #ppId;", conn))
{
selectPriser.Parameters.AddWithValue("#ppId", prisId);
using (SqlDataReader readerPriser = selectPriser.ExecuteReader())
{
if (readerPriser.Read())
{
// ...
using (SqlCommand selectBrugere = new SqlCommand("SELECT id, brugernavn, fornavn, efternavn FROM brugere WHERE Id = #brugerid;"){
string Brugerid = Session["id"].ToString();
selectBrugere.Parameters.AddWithValue("#brugerid", Brugerid);
using (SqlDataReader readerBrugerid = selectBrugere.ExecuteReader()){
if (readerBrugerid.Read()){
// ...
}
}
}
}
}
}
}

C# SQL multiple query results into diffrent textbox

So I'm having this :
Conn.Open();
SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
SqlDataReader DR3 = Comm3.ExecuteReader();
And there is multiple results,how can I now move each of them in diffrent textbox (i already created textboxes? Till now i only managed to get same result into them.
this is normally how i do it....
SqlConnection cn = new SqlConnection("my connection string");
cn.Open();
string sql = "select * from table where column = whatever";
using (SqlCommand cmd = new SqlCommand(sql,cn))
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
myTextBox1.Text = (string)dr["Column1"];
myTextBox2.Text = (string)dr["Column2"];
myTextBox3.Text = (string)dr["Column3"];
}
dr.Close();
}
cn.Close();
just make sure you are aiming the right column name while looping through them, and cast correctly.
You need to loop through each of the item in the Database table. Think of a foreach loop, where you simply just go through each item and work on it similarly.
Here is a sample for that,
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
textBox.Text = reader[0];
}
}
This will add the value of reader's first column (answer) to the textBox. Now make sure you're calling correct textBox to add the value to.
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program Do give this article a read.

Checking the number of rows returned from MySQL Data Reader

I am currently working on an C# project and I am trying to get the number of rows returned from MySQL Data Reader.
I know there is no direct function so I am trying to write my own. In the function, I pass it the MySQLDataReader object and then loop through the MySQL Data Reader and increment a counter and return the value of the counter.
This then seems to lock up the program, I guess because I am Reader.read() after I've got the count I'm already at the end. Instead I have tried creating a copy of the reader and then loop through the temp version but I get the same result.
Below is my code where I am executing the query and calling the function.
string query = "SELECT * FROM reports, software, platforms, versions "
+ "WHERE EmailVerified = #verified AND reports.SoftwareID = software.id AND reports.PlatformID = platforms.id "
+ "AND reports.VersionID = versions.id AND BugReportAcceptedNotificationSent = #notificationSent";
using (MySqlCommand cmd = new MySqlCommand(query, db.conn))
{
cmd.Parameters.AddWithValue("#verified", "1");
cmd.Parameters.AddWithValue("#notificationSent", "0");
using (MySqlDataReader reader = cmd.ExecuteReader())
{
totalEmails = HelperClass.totalRowsInMySQLDataReader(reader);
while (reader.Read())
{
currentEmailCount++;
EmailNotifications emailNotification = new EmailNotifications(reader);
emailNotification.sendNewBugReportAfterVerificationEmail(currentEmailCount, totalEmails);
}
}
}
Below is my function that gets the row count
public static int totalRowsInMySQLDataReader(MySqlDataReader reader)
{
MySqlDataReader tempReader = reader;
ILibraryInterface library = GeneralTasks.returnBitsLibrary(Configuration.databaseSettings, Configuration.engineConfig.logFile);
string methodInfo = classDetails + MethodInfo.GetCurrentMethod().Name;
try
{
int count = 0;
while (tempReader.Read())
{
count++;
}
tempReader = null;
return count;
}
catch (Exception ex)
{
string error = string.Format("Failed to get total rows in MySQL Database. Exception: {0}", ex.Message);
library.logging(methodInfo, error);
library.setAlarm(error, CommonTasks.AlarmStatus.Medium, methodInfo);
return -1;
}
}
Make use of a DataTable to load your results, e.g.
DataTable dt = new DataTable();
dt.Load(reader);
int numberOfResults = dt.Rows.Count;
You can then also iterate over the rows to read the values, e.g.
foreach(DataRow dr in dt.Rows)
{
var value = dr["SomeResultingColumn"]
}
The other option is to issue two separate SQL statements, however you would need to ensure both statements were enclosed within a transaction with a Serializable isolation level, this is needed to make sure records aren't inserted between the execution of the two SQL statements.
To avoid multiple queries, how about including the total in the select itself?
SELECT COUNT(*) AS TotalNORows, * FROM reports, software, platforms, versions etc
i think without executing another command it's not possible...as there is no method available for count in reader class
you can try this... if it works..
string query = "SELECT * FROM reports, software, platforms, versions "
+ "WHERE EmailVerified=#verified AND reports.SoftwareID=software.id AND reports.PlatformID=platforms.id "
+ "AND reports.VersionID=versions.id AND BugReportAcceptedNotificationSent=#notificationSent";
using (MySqlCommand cmd = new MySqlCommand(query, db.conn))
{
cmd.Parameters.AddWithValue("#verified", "1");
cmd.Parameters.AddWithValue("#notificationSent", "0");
using (MySqlDataReader reader = cmd.ExecuteReader())
{
// create a new connection db.conn2 then
MySqlCommand cmd2 = new MySqlCommand(query, db.conn2))
cmd2.Parameters.AddWithValue("#verified", "1");
cmd2.Parameters.AddWithValue("#notificationSent", "0");
MySqlDataReader reader2 = cmd2.ExecuteReader();
int numberofrow=0;
while(reader2.Read())
numberofrow++;
//your codes......
}
Was working on the same problem. I hate having to iterate if a method is already available, but this is was the shortest bit I could come up with:
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader reader = cmd.ExecuteReader();
int rowcount = 0;
while(reader.Read()){
rowcount++;
}
First, create this class:
public static class Extensions
{
public static int Count(this MySqlDataReader dr)
{
int count = 0;
while(dr.Read())
count++;
return count;
}
}
This will implement .Count () on MySqlDataReader.
int count = reader.Count();
Exemple:
string sql= "SELECT * FROM TABLE";
MySqlCommand cmd = new MySqlCommand(sql, connection);
MySqlDataReader reader = cmd.ExecuteReader();
int count = reader.Count();
Maybe you could look things the other way around
You could just do a select count(*) and get the row count
or
use a data adapter to fill a container (like a DataTable) and count the rows
Unfortunatelly solution from Jan Van #Herck will return one row only, so in case you are interested in getting all rows and their number in one select, this isn't what you need.
In that case I suggest uou to try this:
select * , (select count(*) from my_table) AS numRow from my_table;
or read this:
Getting total mysql results returned from query with a limit: FOUND_ROWS error
You can use follwoing SQL Query to get the total rows Count.
SELECT COUNT(*) FROM [MYTABLE]
from the Code you can use ExecuteScalar() method to get the total number of rows returned by QUERY.
Try This:
int GetRowsCount(MySqlCommand command)
{
int rowsCount=Convert.ToIn32(command.ExecuteScalar());
return rowsCount;
}
Use above function as below:
MySqlCommand command=new MySlCommand("Select count(*) from MyTable",connectionObj);
int totalRows = GetRowsCount(command)
OleDbDataReader dbreader = new OleDbDataReader();
int intcount = 0;
if (dbreader.HasRows == true)
{
if (dbreader.Read())
{
intcount = dbreader.RecordsAffected;
}
}
"dbreader.RecordsAffected" will give you the number rows changed,inserted or deleted by the last statement of SQL

MySql "Select Where" and C#

How can i read the return value from "Select Where" statement , every time i run no return value appear in the label, and no syntax error.
command.CommandText = "select product_price from product where product_name='"+x+"';";
connection.Open();
Reader = command.ExecuteReader();
while(Reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
connection.Close();
If the product_price column is not of type TEXT in MySQL, the Reader.GetString(0) will (depending on how the reader was implemented by Oracle) throw an Exception or return an empty string. I would think the latter is happening.
Retrieving the value through a DataReader requires you to know the data type. You can not simply read a string for every type of field. For example, if the field in the database is an Integer, you need to use GetInt32(...). If it is a DateTime use GetDateTime(...). Using GetString on a DateTime field won't work.
EDIT
This is how I'd write this query:
using (MySqlConnection connection = new MySqlConnection(...))
{
connection.Open();
using (MySqlCommand cmd = new MySqlCommand("select product_price from product where product_name='#pname';", connection))
{
cmd.Parameters.AddWithValue("#pname", x);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
sb.Append(reader.GetInt32(0).ToString());
Price_label.Content = sb.ToString();
}
}
}
To append to my comment, your approach has three problems which are not part of your problem:
SQL-Injection, always use parameterized queries.
Leaking resources, IDisposable-Objects need to be treated properly.
Bad habits, "" + string for casting is...uhhh...not good and not necessary.
So, a more correct version for your code would look like this:
// using utilizes the IDisposable-Interface, whcih exists to limit the lifetime
// of certain objects, especially those which use native resources which
// otherwise might be floating around.
using(YourConnectionType connection = new YourConnectionType("connectionstring"))
{
connection.Open(); // You might want to have this in a try{}catch()-block.
using(YourCommandType command = connection.CreateCommand())
{
command.CommandText = "select product_price from product where product_name=#NAME;";
command.Parameters.Add("NAME", YourTypes.VarChar);
command.Parameters[0].Value = x; // For your own sanity sake, rename that variable!
using(YourReaderType reader = command.ExecuteReader())
{
while(reader.Read()) // If you're expecting only one line, change this to if(reader.Read()).
{
Price_label.Content = reader.GetString(0);
}
}
}
} // No need to close the conenction explicit, at this point connection.Dispose()
// will be called, which is the same as connection.Close().
you have to create a variable of your reader
command.CommandText = "select product_price from product where product_name='"+x+"';";
try {
connection.Open();
SqlReader reader = command.ExecuteReader();
while(reader.Read()){
Price_label.Content = "" + Reader.GetString(0);
}
} catch (Exception) {}
finally {
connection.Close();
}
You should write #pname without '' otherwise it won't work.
instead of:
select product_price from product where product_name='#pname'
you should write like this:
select product_price from product where product_name=#pname

Categories