What I am expecting my code to do is gather the top ten records that have an 'I' in the SQLMigrationFl field, and then process those ten records by removing that 'I' value. Below is the portion of code that handles this.
string inProgressQuery = "SELECT TOP 10 IDType, ID, Program, Date, Body,
AcctNo, ANPACAcctID, ANPACClientID, TEAMID,
ImportDate, AnnualReview, TeamGUID,
ANPACClientLastName, ANPACClientFirstName, " +
"PolicyNumber, AccountOwnerLastName,
AccountOwnerFirstName, SCRACF, SCDateTime, NoteID
FROM NoteTable WHERE SQLMigrationFl = ?";
command = new OleDbCommand(inProgressQuery, connection);
command.Parameters.AddWithValue("SQLMigrationFl", "I");
reader = command.ExecuteReader();
if(reader.HasRows)
{
while(reader.Read())
{
//clear the In Progress flag
query = "UPDATE NoteTable SET SQLMigrationFl = ? WHERE
NoteTable.NoteID = " + reader[19].ToString();
command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("SQLMigrationFl", DBNull.Value);
reader = command.ExecuteReader();
}
}
What I am finding is that the query returns one value, and processes it. Then in five seconds it finds another record and reprocesses that one. *Five seconds is just a delay we have set in code to check for more records to be processed. It processes one record at a time, rather than grabbing ten and processing those at once within the same while loop. Is something wrong with my code or query?
Thanks for the help.
The culprit is your reassigning of the data reader using reader = command.ExecuteReader();. That will now return 1 result and your next loop will be over that 1 result. Regardless for non SELECT queries use ExecuteNonQuery instead.
Other places that you can update your code to be "better" are
Use parameters whenever you have values that you want to use in your sql statements.
Always specify the type for all your parameters.
Always wrap your types instances that implement IDisposable in using blocks to ensure resources are cleaned up.
I also recommend you not share connection instances, below it seems that there might be a static connection somewhere. It would be best to not share one and create/open one when you need it and then close/dispose it.
string inProgressQuery = "SELECT TOP 10 IDType, ID, Program, Date, Body,
AcctNo, ANPACAcctID, ANPACClientID, TEAMID,
ImportDate, AnnualReview, TeamGUID,
ANPACClientLastName, ANPACClientFirstName, " +
"PolicyNumber, AccountOwnerLastName,
AccountOwnerFirstName, SCRACF, SCDateTime, NoteID
FROM NoteTable WHERE SQLMigrationFl = ?";
using(var command = new OleDbCommand(inProgressQuery, connection))
{
// I guessed on the type and length
command.Parameters.Add(new OleDbParameter("SQLMigrationFl", OleDbType.VarChar, 10)).Value = "I";
using(var reader = command.ExecuteReader())
{
while(reader.Read())
{
//clear the In Progress flag
const string UpdateQuery = "UPDATE NoteTable SET SQLMigrationFl = ? WHERE NoteTable.NoteID = ?";
using(var commandUpdate = new OleDbCommand(UpdateQuery, connection))
{
commandUpdate.Parameters.Add(new OleDbParameter("SQLMigrationFl", OleDbType.VarChar, 10)).Value = DBNull.Value;
commandUpdate.Parameters.Add(new OleDbParameter("NoteId", OleDbType.Int)).Value = reader[19];
commandUpdate.ExecuteNonQuery();
}
}
}
}
Related
I am working on a project, where I want to use a SQL command string to sort through my database in ascending order according to one of the columns and then use another command to get the first value that is greater than or equal to a measured value.
For some reason or another my code only prints out 1, no matter what I change the value that is being measured against the database to. I'm not sure if there is an issue with my second SQL command string or if I am messing up with the OleDb Get methods.
I am a bit rusty with my programing so, additional advice would be appreciated.
Here is my code:
bool renew;
string conn = TableSettings.Instance.GetConnectionString();
string readingInDoubles = lblReading.Text;
double dNumber;
renew = Double.TryParse(readingInDoubles, out dNumber);
string SqlCmdSort = "SELECT * FROM Tables ORDER BY Mass ASC";
string SqlCmdCompare = "SELECT * FROM Tabels WHERE Mass >= " + renew;
using (OleDbConnection connect = new OleDbConnection(conn))
{
OleDbCommand command = new OleDbCommand(SqlCmdSort, connect);
OleDbCommand command2 = new OleDbCommand(SqlCmdCompare, connect);
connect.Open();
OleDbDataReader sort = command.ExecuteReader();
while (sort.Read())
{
OleDbDataReader compare = command2.ExecuteReader();
compare.Read();
// compare.GetDouble(0); ignore this.
lblUpperValue.Text = compare[0].ToString();
compare.Close();
}
sort.Close();
connect.Close();
}
I am developing a cricket simulation and i need to retrieve certain statistics from a players data. I've got the following code.
public List<float> BattingData()
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
string query = "SELECT [INNS], [NOT OUTS], [AVG] FROM [" + batTeam + "] WHERE [Player] = '" + name + "';";
SqlCommand com = new SqlCommand(query, con);
con.Open();
using (SqlDataReader reader = com.ExecuteReader())
{
if(reader.HasRows)
{
while (reader.NextResult())
{
Innings = Convert.ToInt32(reader["INNS"]);
NotOuts = Convert.ToInt32(reader["NOT OUTS"]);
Avg = Convert.ToSingle(reader["AVG"]);
}
}
}
con.Close();
OutRatePG = (Innings = NotOuts) / Innings;
OutRatePB = OutRatePG / 240;
RunsPB = Avg / 240;
battingData.Add(OutRatePB);
battingData.Add(RunsPB);
return battingData;
}
The error that I am getting is that when I try to divie by 'Innings' it is saying cannot divide by zero, so I think the variables are being returned as zero and no data is being assigned to them.
This line is the issue:
while (reader.NextResult())
What this does is move the reader to the next resultset, ignoring the rest of the rows unread. To advance a reader to the next row, you need to call reader.Read() instead.
You have some other issues with your code:
You appear to have a separate table for each team. This is incorrect database design. You should create a Team table, with each team in it, and then foreign key your TeamResults table to it. Query it using INNER JOIN.
You are concatenating user-entered values to your query. This leaves you open to SQL injection attacks. Use parameters instead. (You cannot parameterize a table name, another reason you should do as above 1.)
You do not need to check for HasRows. If there are no rows, Read() will return false.
It looks like you only want one row. If that is the case you don't want a while(reader.Read()) loop, instead if(reader.Read()). (If you only need a single value, you can refactor the code to use command.ExecuteScalar().)
In database records check if value for Innings has 0
also you can try the below code before performing any operation.
> if(Innings>0) { OutRatePG = (Innings - NotOuts) / Innings; }
I'm trying to get the value of a Field (User Access level it's 1 or 2 in string format) after login
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dsms.accdb");
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username='" + textusername.text + "'", connection);
reader = command.ExecuteReader();
if( reader.HasRows)
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(1);
}
else
MessageBox.Show("failur", "status");
connection.Close();
I did execute the code in Access and it's was totally fine
but in the program, it says "No data exist for the row/column"
The main problem in your code is the fact that you need to call reader.Read() to get anything out from a DataReader. Just calling HasRows doesn't position the reader on the first record of your query.
There are other problems in your code.
Disposable objects like connections, commands and readers should be created in a using statement to ensure proper disposition after use and because you have only one field in your query, you should use the index 0 to retrieve it not 1.
Finally the most important one. You should NEVER concatenate strings to build an sql query. In this way a malicious user could write anything in your textbox, even valid sql commands that could be executed against your database. It is called Sql Injection and if you search for these terms you will find very detailed discussions about it. However, to avoid this problem (and others like parsing input with apostrophes) you use a parameterized query like below.
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username=#name", connection);
{
connection.Open();
command.Parameters.Add("#name", OleDbType.VarWChar).Value = txtusername.text;
using(OleDbDataReader reader = command.ExecuteReader())
{
if( reader.Read())
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(0);
}
else
MessageBox.Show("failur", "status");
}
}
So i have a class Take for connecting to mysql. In that class I have a method to call a query to take the last record from mysql table.
public void Balance()
{
string query = "SELECT balance FROM history ORDER BY id DESC LIMIT 1 ";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}
}
In the main form I'm calling that class and that method
take.Balance();
I know, that from code above, i don't get any value but NULL, so i am asking how i can take value from that query and put it in the TextBox in the main form?
Personally, I think you should improve your basic knowledge of programming. There are two big problems in your example code:
You want to get the value, but your function is void, not return anything even set the value to some variable
ExecuteNonQuery is not your case.
For example:
public string Balance()
{
string query = "SELECT balance FROM history ORDER BY id DESC LIMIT 1 ";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
return cmd.ExecuteScalar();
}
}
Let's have look:
// You probably want to return value: decimal, not void
public decimal Balance() {
// Make sql readable
string query =
#"SELECT balance
FROM history
ORDER BY id DESC
LIMIT 1 ";
// do not cache connection, but create a new one instead
using (MySqlConnection conn = new MySqlConnection(connectionStringHere)) {
conn.Open();
// wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(query, conn)) {
// you want to return values: ExecuteReader (or ExecuteScalar)
// instead of ExecuteNonQuery
using (var reader = cmd.ExecuteReader()) {
if (reader.Read())
return Convert.ToDecimal(reader.GetValue(0));
else
return 0m; // cursor is empty, let's return 0
}
}
}
}
There are two things to consider. First, the query
"SELECT balance FROM history ORDER BY id DESC LIMIT 1"
is a query in the sense that some useful data from the database should be returned, it should not be executed with a the method ExecuteNonQuery, which is intended to return the number of rows affected by a non-query statement. Second, the return type of Balance would have to be changed to some other type than void, say int or something similar, which would have to be returned to the caller.
I need to retrieve a value from a field in database. I have the used following code. but the value checkOrderId (which I need) shows the SQL string instead of the value from database. I don't know why it is doing so. Could somebody help me please?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
I am new and dont have reputation to answer my question immediately. With everybody's help, i got this one solved...Great help, thanx everybody...following is my code.
string connectionString = "Data Source = EAEDEV;Initial Catalog = GIS; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
You need to execute the query and check the results, here you are just comparing a string with the query SQL.
Please see here
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03
for a tutorial.
Your expectation of the result being set into checkOrderId is incorrect. In this instance checkOrderId is just the query to execute and not the actual result.
You need to read the value back from executing the command:
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand("Select TOP 1 OrderID From [GIS].[SecondaryTraffic].[PotentialBackHauls] ORDER BY InsertDate DESC", connection))
{
connection.Open();
object result = comm.ExecuteScalar(); // This is the key bit you were missing.
if (result != null)
{
// You can cast result to something useful
int orderId = (int)result;
}
} // Both comm and connection will have Dispose called on them here, no need to Close manually.
ExecuteScalar returns the value in the first cell (ie, column 1 row 1) as an object that you can cast to a better type (depending on what type it was in the result-set schema).
If you need to read multiple values, you need to look at ExecuteReader.
There are also other ways of doing this using output parameters, but that would pollute the point of the answer.
You can add space to your query
"Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
Nota : I suggest you to use AddWithValue method with your parameter
string checkOrderId = "Select TOP 1 OrderID From #tableName ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
cmd.Parameters.AddWithValue("#tableName", tableName );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
You don't actually run your command anywhere. Instead of the commented-out cmd.ExecuteNonQuery, you should look into the ExecuteScalar method, which allows you to read back a single result value from a query - which is what your query returns.
Add
int i = (Int32) cmd.ExecuteScalar();
right after
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
then the variable i will contain the order id
No, this is not correct. You are comparing the variable orderId to your query string. I doubt that's what you want to do. I imagine you'd be better off calling cmd.ExecuteScalar() to retrieve the actual OrderID value. As noted by other answers, your query string is missing a space. But most importantly, it is bad practice to construct SQL queries in code. Although I can't see a security issue with this code, if you continue to use this method you will probably write code that is vulnerable to SQL injection. I recommend you learn to either use parameters or LINQ to build your queries.