i am having a hard time to display my count code to my label text. here is my code and please tell me how to solve this problem.
ordering_and_billing.dBase dBase = new ordering_and_billing.dBase();
var mydbconnection = new dBase.dbconnection();
string sql = "SELECT * FROM `order` WHERE eventdate='" + lbldte.Text + "'";
MySqlCommand cmd = new MySqlCommand(sql, mydbconnection.Connection);
mydbconnection.Connection.Open();
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Int32 count = (Int32)cmd.ExecuteScalar();
string disp = count.ToString();
lblcount.Text = disp;
}
}
just use count function:
string sql = "SELECT COUNT(*) FROM `order` WHERE eventdate='" + lbldte.Text + "'";
also don't use ExecuteReader, use ExecuteScalar function if you want a single value like a count value:
lblcount.Text =cmd.ExecuteScalar().toString();
You should use SELECT COUNT(*) if all you want is the record count.
string sql = "SELECT COUNT(*) FROM `order` WHERE eventdate='" + lbldte.Text + "'";
However, keep in mind that rdr.Read() reads a new row from the sql query. Every time you get a new row, you're trying to rerun the sql command (which I'm guessing crashes) and then assign the count label. So you're trying to assign the count label count times. Use this construct instead:
int count = 0;
while (rdr.Read())
{
count++;
}
lblcount.Text = count.ToString(); //only assigns to the Text property once
never mind guys i got my answer now.
ordering_and_billing.dBase dBase = new ordering_and_billing.dBase();
var mydbconnection = new dBase.dbconnection();
string sql = "SELECT * FROM `order` WHERE eventdate='" + lbldte.Text + "'";
MySqlCommand cmd = new MySqlCommand(sql, mydbconnection.Connection);
mydbconnection.Connection.Open();
MySqlDataReader rdr = cmd.ExecuteReader();
int count = 0;
while (rdr.Read())
{
count ++;
}
lblcount.Text = count.ToString();
Related
I'm trying to retrieve multiple cells in different rows where the correct owner exists, but I'm only being able to retrieve the first match and it stops there, I've tried using it with a for, but I don't think .ExecuteScalar() is the way to do this. Maybe I'm just stupid and doing it completely wrong.
Code:
checkPlayerName = API.getPlayerName(player);
string checkOwnedCars = "SELECT COUNT(*) FROM [carOwners] WHERE Owner='" + checkPlayerName + "'";
con.Open();
SqlCommand checkCarsCount = new SqlCommand(checkOwnedCars, con);
int carsCountToVar = Convert.ToInt32(checkCarsCount.ExecuteScalar());
con.Close();
for (int i = 0; i < carsCountToVar; i++)
{
string displayCars = "SELECT LP FROM [carOwners] WHERE Owner='" + checkPlayerName + "'";
con.Open();
SqlCommand displayCarsCMD = new SqlCommand(displayCars, con);
string displayCarsToVar = displayCarsCMD.ExecuteReader().ToString();
API.sendChatMessageToPlayer(player, "Owned Vehicle: " + displayCarsToVar.ToString());
con.Close();
}
Table
For example, LP on 2nd and 3rd row are the ones that I want to store since both belong to the same owner, yet only first cell data (1337) is displaying.
You are not iterating the results you are getting from query.
Plus always use Parameterized queries to prevent SQL Injection Attacks
SqlCommand command = new SqlCommand("SELECT LP FROM [carOwners] WHERE Owner=#checkPlayerName", con);
command.Parameters.AddWithValue("#checkPlayerName",checkPlayerName);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader["id"]));
//API.sendChatMessageToPlayer(player, "Owned Vehicle: " + reader["id"].ToString());
}
}
conn.Close();
I got some problem when I run my code. It says
Data type mismatch in criteria expression
in
OleDbDataReader reader = command.ExecuteReader();
I don't know what the mistake is. Can anyone help me ?
private void JumlahLembar()
{
foreach (DataGridViewRow row in JadwalisiGV.Rows)
{
int lim30den50tot;
if (!row.IsNewRow)
{
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();
kon.Open();
command.CommandText = "select * from [StokLembar$] where [Limit] = '" + row.Cells["Limit"].Value + "'";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int den50 = int.Parse(reader["Lembar Denom 50"].ToString());
int den100 = int.Parse(reader["Lembar Denom 100"].ToString());
if (row.Cells["Limit"].Value.ToString() == "30")
{
lim30++;
lim30den50tot = lim30 * lim30 * 2 * 1000000 * den50 * 50000;
TotalDen50Box.Text = lim30den50tot.ToString();
}
}
kon.Close();
}
}
}
Go for a parameter based query running under a using as:
using (OleDbCommand command = conn.CreateCommand())
{
// create command with placeholders
cmd.CommandText =
"SELECT * FROM [StokLembar$] WHERE [Limit] = #limit ";
// add named parameters
command.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#limit", row.Cells["Limit"].Value)
});
// execute
command.ExecuteNonQuery();
}
I'm assuming [Limit] is a string type in the database. Your mileage may vary.
As pointed out by #Patrick-Hofman, the database can now figure out on its own.
You set Limit as text column, most probably it may be number. try below without quotes
command.CommandText = "select * from [StokLembar$] where [Limit] = " + row.Cells["Limit"].Value`
You better use parameters instead of concatenating SQL statement to avoid sql injection attacks.
First thing, my question is quite complicated and I am not really proficient to explain it in details, so I would like to say sorry in advance.
Ok, here is the thing. I execute this query
string count = "SELECT Count(*) FROM Student WHERE IntakeID = 'MYVALUE'"
And it would return the number of 10. So I continue with this code:
SqlCommand cmd = new SqlCommand(count, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
for (int x = 0; x < temp; x++)
{
string query = "INSERT INTO Docket (DocketNo, StudentID) VALUES ('" + getUniqueKey() + "','(SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE')')
}
PS: getUniqueKey() is a method to get my generated unique key.
Is this piece of code technically correct? The result I want to have is something like below:
+-----------+-------------+
| DocketNo | StudentID |
+-----------+-------------+
| 18590394 | TP123456 |
| 09141563 | TP012457 |
| 58293495 | TP049185 |
+-----------+-------------+
If you are unclear of my question, I will try my best to make it clearer. Sorry for inconvenience.
UPDATE (ANSWER):
With the help from Paparazzi (Thanks!) for his code, I modified and come up with my own solution.
string count = "SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE'"
SqlCommand cmd = new SqlCommand(count, conn);
string query = "INSERT INTO Docket (DocketNo, StudentID) VALUES ";
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
var loop = true;
while (loop)
{
loop = rdr.Read();
if (!loop)
{
//When end of rows and no more data to be retrieve, it removes the last "," from the query.
char[] trimChar = { ',' };
string newQuery = query.TrimEnd(trimChar);
cmd.CommandText = newQuery;
}
else {
query += "('" + GetUniqueKey() + "','" + rdr.GetString(0) + "')";
query += ",";
}
}
}
cmd.ExecuteNonQuery();
conn.Close();
So actually while looping on the SqlDataReader, the query would generate in the background something like:
INSERT INTO Docket(DocketNo, StudentID) VALUES ('1562456','TP028800'), ('1465446','TP028801'),..........('4939104','TP028810'),
Take note there will be a "," comma at the end of the query because of the query += ",";. And when the SqlDataReader returns no more rows, it would execute the if(!loop) statement to remove the last "," (comma) from the query.
If you are unclear what is the += for, read more at https://msdn.microsoft.com/en-us/library/sa7629ew.aspx
UPDATE 2:
#Paparazzi has come up with a much more efficient and performance-wise method if you are managing a huge data. Look for his code in his own post. :)
string count = "SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE'"
SqlCommand cmd = new SqlCommand(count, conn);
string query = "INSERT INTO Docket (DocketNo, StudentID) VALUES ";
conn.Open();
bool first = true;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (first)
first = false;
else
query += ", "
query += "('" + getUniqueKey() + "', '" + rdr.GetString(0) + "')";
}
}
if (!first)
{
cmd.CommandText = query + ";";
cmd.ExecuteNonQuery();
}
conn.Close();
StringBuilder is faster than += on string
And multiple values is limited to 1000 (I think) but WAY more efficient than individual inserts
So if you can get more than 1000 then need to add a counter and fire off the insert
string getID = "SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE'"
SqlCommand cmd = new SqlCommand(getID , conn);
string insert = "INSERT INTO Docket (DocketNo, StudentID) VALUES ";
Int32 count = 0;
StringBuiler sb = new StringBuiler();
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (count == 0)
{
sb.Clear();
sb.AppendLine(insert);
}
else
sb.Append(", ")
sb.Append("('" + getUniqueKey() + "', '" + rdr.GetString(0) + "')");
count++;
if(count > 800)
{
count = 0;
cmd.CommandText = sb.ToString() + ";";
cmd.ExecuteNonQuery();
// most likely need a separate cmd here has a open reader
// will leave that as an exercise for you
// could even go asynch if you want to get faster
// or you could just build up multiple inserts on sb
}
}
}
if (count > 0)
{
cmd.CommandText = sb.ToString() + ";";
cmd.ExecuteNonQuery();
}
conn.Close();
SqlCommand cmd = new SqlCommand(count, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
for (int x = 0; x < temp; x++)
{
string query += "INSERT INTO Docket (DocketNo, StudentID) VALUES ('" + getUniqueKey() + "','(SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE')');";
}
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteQuery();
I'm trying to populate a Gridview with results from loop. But I'm getting only last result in the loop.
I think GridView is being overwritten on every time the for loop is being executed.
Can you people help me to remove this problem please.
for (int j = 0; j < i; j++)
{
Label1.Text += fipath[j];
Label1.Text += "-------------";
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='" + NAME + "' AND FilePath='" + fipath[j] + "'", conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (Role.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
There is more than one problem with this code:
seems like if Role== "admin" you don't need to query db at all
DataSource of the grid is overridden on every loop iteration, this is why you see only the last value.
use parameters for SqlCommand to prevent SQL injection.
don't run string concatenation in the loop. Use StringBuilder instead
use using for your connection. The code is cleaner this way.
The fix could look like this:
if (Role != "admin")
return;
var dataTable = new DataTable();
var stringBuilder = new StringBuilder();
using (var connection = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true"))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "Select * from FileUpload where UploadedBy = #UploadedBy AND FilePath = #FilePath";
command.Parameters.AddWithValue("UploadedBy", NAME);
var filPathParameter = command.Parameters.Add("FilePath", SqlDbType.VarChar);
for (int j = 0; j < i; j++)
{
stringBuilder.Append(fipath[j]);
stringBuilder.Append("-------------");
filPathParameter.Value = fipath[j];
dataTable.Load(command.ExecuteReader(), LoadOption.PreserveChanges);
}
}
Label1.Text += stringBuilder.ToString();
GridView1.DataSource = dataTable;
GridView1.DataBind();
Also, I don't know how many elements your normal loop is. If it is one or two and you have appropriate indexes in FileUpload table then it is ok to leave as is. However, if you need to do the for many times you should consider switching to a single query instead
For example:
var filePathes = string.Join(",", fipath.Select(arg => "'" + arg + "'"));
var command = "Select * from FileUpload where UploadedBy = #UploadedBy AND FilePath in (" + filePathes + ")";
This query is SQL injection prone. And has a 2100 elements limit in MS SQL.
There is more than one way to approach this. Depends on your DBMS and requirements.
Use the in clause in SQL Query and pass the list of ID's in FilePath
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='" + NAME
+ "' AND FilePath in (" + listOfIDs + ")", conn);
Check out these URLs that are related to the use of in clause.
Techniques for In-Clause and SQL Server
Parameterizing a SQL IN clause?
Create a list or BindingSource outside the loop, bind that to your gridview and then add all records to that list or source.
The problem with your current approach is that you are overwriting the records pulled from the database with a new datasource each time, so as you stated, only the last one is "set", and the older assignments are disposed of.
I want to get the retrived records count from the OleDbDataReader in C# ?
strQuery = "SELECT * FROM Table_Name" ;
dbCommand = new OleDbCommand(strQuery, dbConnection);
dbReader = dbCommand.ExecuteReader();
//Now how to get RowCount from the Table after this.
Any help is appreciated.
Thanks.
For more detail : Get row count by 'ExecuteScalar'
Make use of ExecuteSclar() rather than going for read function.
SqlCommand cmd = new SqlCommand("SELECT count(*) FROM " + Table_Name, conn);
try
{
conn.Open();
int total = (Int32)cmd.ExecuteScalar();
}
You could change the query to:
strQuery = "SELECT count(*) as RowCount, * FROM " + Table_Name;
That would allow you to retrieve the rowcount like:
dbReader.Read();
var rowCount = (int)dbRead["RowCount"];
This will do it, but there are likely better ways:
int i = 0;
While (dbReader.Read()){
i++;
}