Get retrived records count from OleDbDataReader in C#? - c#

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++;
}

Related

Selecting and retrieving multiple cells in different rows

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();

Data type mismatch in criteria expression excel C#

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.

how to display count in label text?

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();

How to define a limit as parameter?

Given conn is an OdbcConnection object and count is an int, how would I use count as parameter for my query?
...
var query = conn.CreateCommand();
query.CommandText = "select top ? * from players order by Points desc";
query.Parameters.Add("top", OdbcType.Int).Value = count;
var reader = query.ExecuteReader();
while (reader.Read())
{
...
}
...
This way I get a syntax error ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '#P1'.
If it is not possible the way I tried how would I do it the correct way instead?
You can also use SET ROWCOUNT the advantage is you can use a integer as parameter and avoid dynamic queries.
SET ROWCOUNT #top;
select * from table;
SET ROWCOUNT 0;
read the documentation
You can do:
query.CommandText = "select top (#topparameter) * from players order by Points desc";
query.Parameters.AddWithValue("#topparameter", count.ToString());
If you are using SqlServer then use SqlConnection and SqlCommand like:
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
using (SqlCommand query = new SqlCommand("select top (#topparameter) * from players order by Points desc", conn))
{
query.Parameters.AddWithValue("#topparameter", count.ToString());
var reader = query.ExecuteReader();
while (reader.Read())
{
}
}
}

How to check if record exists or not and insert in ms access database in c#

I want to check if record exists or not if it exists i dont want to insert if it bot i want to insert the data in ms access database in c#.
OleDbCommand cmd = new OleDbCommand("insert into MyTable values('" + test + "','" + test + "','" + "123" + "');", con);
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);
temp = 0;
try
{
con.Open();
string count = (string)cmd1.ExecuteScalar();
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("One Record Added");
}
else
{
MessageBox.Show("Record not added");
}
}
catch
{ }
Can Anyone suggest me some code.
Thanks In Advance.
Filter your Select query on the basis of some key . Check if it returns for existence or non-existence of the particular record and do the processing required .
string cmdStr = "Select count(*) from MyTable where id = 1"; //get the existence of the record as count
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
int count = (int)cmd.ExecuteScalar();
if(count >0)
{
//record already exist
}
Modify this line
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);

Categories