How to count all rows in a data table c# - c#

So I am creating a messaging application for a college project and I have a database of Users in Access, I have linked the database correctly and can execute statements but I am struggling with one problem, how to count the number of rows in a data table.
In fact, all I want to do is to count the total number of users and my teacher told me to get the data into a DataTable and count the number of rows. However, no matter how many users I have in the database, it always returns as 2.
int UserCount = 0;
using (OleDbConnection cuConn = new OleDbConnection())
{
cuConn.ConnectionString = #"DATASOURCE";
string statement = "SELECT COUNT(*) FROM Users";
OleDbDataAdapter da = new OleDbDataAdapter(statement, cuConn);
DataTable Results = new DataTable();
da.Fill(Results);
if (Results.Rows.Count > 0)
{
UserCount = int.Parse(Results.Rows[0][0].ToString());
}
}
The above code is a copy of what I was sent by my teacher who said it would work. Any help would be appreciated.
Also, sorry if this is a waste of time, still getting used to this StackOverflow thing...

Try replace Users with [Users]?
Because Users may be a key word of database.
Also the simpler way to get aggregate numbers is by ExecuteScalar method.
using (OleDbConnection cuConn = new OleDbConnection())
{
cuConn.ConnectionString = #"DATASOURCE";
string statement = "SELECT COUNT(*) FROM [Users]";
OleDbCommand cmd = new OleDbCommand (statement, cuConn);
cuConn.Open();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
//
}
}

I successfully used your exact code (except the connection string) with sql server so maybe there is a problem with your #"DATASOURCE" or MS Access.

Related

Select after bulk insert doesn't work in MS access database

There is a windows form application. I am using the MS Access database for some data manipulation. I want to copy data from one database to another. The table name, schema and the data types are same in both the tables.
I am using the below query to bulk insert data in destination database by selecting data from the source database.
INSERT INTO [Table1] IN 'C:\Data\Users.mdf' SELECT * FROM [Table1]
After data is inserted, I am querying to the target table to fetch the inserted data. I am using OleDbConnection for performing the database operations.
The issue I am facing here is that, after the above mentioned INSERT query is executed when I am executing the SELECT statement to fetch the data, I am not getting the data. However, when I am checking in debugging mode then I am getting the data.
I noticed that if I am waiting for some time after the INSERT statement is executed then the data is coming correctly. So I assume that it needs some time(delay?) to complete the bulk insert operation.
I tried providing Task.Delay(20000) after the INSERT query execution but no luck. Could someone help me here, how I can resolve this issue? Any help is highly appreciated.
I didn't find a good way to handle this but did a work around for the same. After data is inserted into the table, I am firing another query to check whether there is any data in the inserted table or not. This happens in a do..while loop like follows. The table is dropped every time the operation is completed.
var insertQuery = "INSERT INTO [Table1] IN 'C:\Data\Users.mdf' SELECT * FROM [Table1]";
ExecuteQuery(insertQuery, connProd);
var count = 10;
do
{
var selectQuery = "SELECT TOP 1 * FROM " + tableProdCopy;
var dtTopRowData = GetQueryData(selectQuery, connOther);
if (dtTopRowData != null && dtTopRowData.Rows.Count > 0)
{
count = 0;
break;
}
System.Threading.Thread.Sleep(2000);
count = count - 1;
} while (count > 0);
private DataTable GetQueryData(string query, OleDbConnection conn)
{
using (OleDbCommand cmdOutput = new OleDbCommand(query, conn))
{
using (OleDbDataAdapter adapterOutput = new OleDbDataAdapter(cmdOutput))
{
var dtOutput = new DataTable();
adapterOutput.Fill(dtOutput);
return dtOutput;
}
}
}
private void ExecuteQuery(string query, OleDbConnection conn)
{
using (OleDbCommand cmdInput = new OleDbCommand(query, conn))
{
cmdInput.ExecuteNonQuery();
}
}

Getting a selection of rows into C# from SQL CE

I am relatively new to C# and am developing an application that communicates with a local database (SQL Compact 3.5). I am fine with running standard select statements - but when it comes to getting that data into C# - I get a bit lost.
What I have so far is a 'delete' query that deletes all rows named 'Master'.
Now I have worked out that I actually need to get the IDs of those rows before I delete them (for database integrity purposes). I have no problems running a standard select query - my problem is getting a selection of rows from SQL CE into a C# application (using arrays or datatables or whatever is most logical/convenient).
This is what I have at the moment, but it only returns one value, not a selection:
string sql = "select listid from list where ShortDesc='Master'";
SqlCeCommand cmdGetOldMasterId = new SqlCeCommand(sql, DbConnection.ceConnection);
int oldKey = (int)cmdGetOldMasterId.ExecuteScalar();
Console.WriteLine("Old ID: " + oldKey);
I need to be able to do perform a foreach{ } loop on each of the returned rows. Any ideas how I can do this in C#?
You need to use a SqlCeDataReader instead of a ExecuteScalar if you suppose that your sql statement returns more thant one row of data
string sql = "select listid from list where ShortDesc='Master'";
SqlCeCommand cmdGetOldMasterId = new SqlCeCommand(sql, DbConnection.ceConnection);
SqlCeDataReader reader = cmdGetOldMasterId.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader[0].ToString());
// or, if your listid is an integer
// int listID = reader.GetInt32(0);
}
another possibility is to use a SqlCeDataAdapter to fill a DataTable (this is less performant, but more useful if you need to process your data later in a different method)
string sql = "select listid from list where ShortDesc='Master'";
SqlCeCommand cmdGetOldMasterId = new SqlCeCommand(sql, DbConnection.ceConnection);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmdGetOldMasterId);
DataTable dt = new DataTable();
da.Fill(dt);
....
foreach(DataRow r in dt.Rows)
{
Console.WriteLine(r["listid"].ToString());
}
SqlCeCommand has several execution methods
ExecuteNonQuery - to execute sql that does not need to return something
ExecuteScalar - for SELECT queries returning one value (don't mix with one row)
ExecuteReader - for SELECT queries returning >=0 rows
http://msdn.microsoft.com/en-us/library/182ax5k8.aspx
var reader = cmdGetOldMasterId.ExecuteReader();
while(reader.Read())
{
// reader[0], reader[1]...
}

C# Excel result comparation

I have never learned this aspect of programming, but is there a way to get each separate result of a excel query(using OleDB) or the likes.
The only way I can think of doing this is to use the INTO keyword in the SQL statement, but this does not work for me (SELECT attribute INTO variable FROM table).
An example would be to use the select statement to retrieve the ID of Clients, and then compare these ID's to clientID's in a client ListArray, and if they match, then the clientTotal orders should be compared.
Could someone prove some reading material and/or some example code for this problem.
Thank you.
This code fetches rows from a sql procedure. Will probably work for you too with some
modifications.
using (var Conn = new SqlConnection(ConnectString))
{
Conn.Open();
try
{
using (var cmd = new SqlCommand("THEPROCEDUREQUERY", Conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
// Find Id of column in query only once at start
var Col1IdOrd = reader.GetOrdinal("ColumnName");
var Col2IdOrd = reader.GetOrdinal("ColumnName");
// loop through all the rows
while (reader.Read())
{
// get data for each row
var Col1 = reader.GetInt32(ColIdOrd);
var Col2 = reader.GetDouble(Col2IdOrd);
// Do something with data from one row for both columns here
}
}
}
finally
{
Conn.Close();
}

Insert several rows in a gridView without using a 'for' loop

I am creating a Attendance System and using grid view to insert the data. There may be many rows on the grid. All things are going well and data are also entering well. But I am using a for loop to check each row. This make the performance quite slow when the number of rows increases. And also the round trips increases with the growing number of rows.
Can anyone provide a better solution for this?
I have modify my CODE according to u all.....but now a problem has arise it is only inserting the last row of the grid multiple times......Other than this the Code is fine.
MySqlDataAdapter myworkdatta = myworkdatta = new MySqlDataAdapter("SELECT CID,EID,TID,ATTENDENCE FROM EMPLOYEEATT ORDER BY AID DESC LIMIT 1", conn);
DataSet myworkdsatt = new DataSet();
myworkdatta.Fill(myworkdsatt, "EMPLOYEEATT");
int i;
for (i = 0; i < emplist_gv.Rows.Count; i++)
{
string tid = emplist_gv.Rows[i].Cells[6].Value.ToString();
string eid = emplist_gv.Rows[i].Cells[0].Value.ToString();
string atid = emplist_gv.Rows[i].Cells[7].Value.ToString();
MySqlCommand cmdwk = new MySqlCommand("INSERT INTO EMPLOYEEATT (CID,EID,TID,ATTENDENCE) VALUES (#cid,#eid,#tid,#attendence)", conn);
MySqlParameter spcidatt = new MySqlParameter("#cid", calid);
MySqlParameter speid = new MySqlParameter("#eid", eid);
MySqlParameter sptid = new MySqlParameter("#tid", tid);
MySqlParameter spattendence = new MySqlParameter("#attendence", atid);
cmdwk.Parameters.Add(spcidatt);
cmdwk.Parameters.Add(speid);
cmdwk.Parameters.Add(sptid);
cmdwk.Parameters.Add(spattendence);
myworkdatta.InsertCommand = cmdwk;
DataRow drowk = myworkdsatt.Tables["EMPLOYEEATT"].NewRow();
drowk["CID"] = calid;
drowk["EID"] = eid;
drowk["TID"] = tid;
drowk["ATTENDENCE"] = atid;
myworkdsatt.Tables["EMPLOYEEATT"].Rows.Add(drowk);
}
myworkdatta.Update(myworkdsatt, "EMPLOYEEATT");
Considering your 2 select SQL statement doesn't seem to contain anything relevant to the the specific row you can take that out of the loop and just use its values easy enough.
Because you need to do an insert on each row, which I don't understand why, then it seems hard to remove the database hits there.
If you are doing a bulk insert you could look at bulk inserts for MySql: MySql Bulk insert
You can use SqlBulkCopy, it's easy to use. Basically just provide it with a data table (or data reader) and it will copy the rows from that source to your destination table.
Shortly, the code block would look like:
DataTable dataTableInGridView = (DataTable)emplist_gv.DataSource;
using (SqlConnection connection =
new SqlConnection(connectionString))
{
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(dataTableInGridView);
}
catch (Exception ex)
{
// Handle exception
}
}
}

store values from database into combobox

I'm trying to write a program using SQL and OleDB and I get an error while the Program is running.
the program first counts the number of rows in the table(access table which called 'tblCodons')
and storage the number as integer in j.
then the program stores all the rows (from a specific column which called 'codonsFullName') in comboBox1.
the code is below
I get this ERROR:System.Data.OleDb.OleDbException (0x80040E14): Invalid SQL statement;Required values​​' DELETE ',' INSERT ',' PROCEDURE ',' SELECT 'or' UPDATE
the code:
int j=0;
OleDbConnection conn1 = new OleDbConnection(connectionString);
conn1.Open();
string sqlCount= "SET #j= SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons";
OleDbCommand counter = new OleDbCommand(sqlCount, conn1);
counter.ExecuteNonQuery();
conn1.Close();
OleDbConnection conn2 = new OleDbConnection(connectionString);
conn2.Open();
string sqlFill = "SELECT tblCodons.codonsFullName FROM tblCodons";
OleDbCommand fill = new OleDbCommand(sqlFill, conn2);
fill.ExecuteNonQuery();
OleDbDataReader dataReader = fill.ExecuteReader();
dataReader.Read();
for (int i = 0; i < j; i++)
{
comboBox1.Items.Add(dataReader.GetString(i));
}
You seem to need the count only for the loop. Also I do not understand why you are executing fill.ExecuteNonQuery() before executing is as a reader.
Also setting #j (if it did work) in a sql query has no scope to a local variable j in the code you are trying to set.
You should only need the following code (apologies for any syntax errors)
OleDbConnection conn2 = new OleDbConnection(connectionString);
conn2.Open();
string sqlFill = "SELECT tblCodons.codonsFullName FROM tblCodons";
OleDbCommand fill = new OleDbCommand(sqlFill, conn2);
OleDbDataReader dataReader = fill.ExecuteReader();
int j = 0;
if (dataReader.HasRows)
{
while(dataReader.Read())
{
comboBox1.Items.Add(dataReader.GetString(0));
j++;
}
}
Hope that helps
Leaving this answer here as an explanation for fixing your code as it currently exists, but also want to point out that I recommend going with Kamal's solution; it only queries the database once.
This line is probably your error:
string sqlCount= "SET #j= SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons";
change to
string sqlCount= "SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons";
You'll want to change your code to obtain the result of that first query like this:
j = counter.ExecuteScalar();
First, as Kamal Mentioned you can't directly set a variable from a sql query as you are trying to do and as the exception states only "SELECT" , "INSERT","UPDATE" and "DELETE" commands can be use in a query.
Second, I don't know why you need to get the record counts before getting the actual data but if it's really necessary you can write your query like this :
var query="SELECT COUNT(tblCodons.codonsFullName) FROM tblCodons;SELECT tblCodons.codonsFullName FROM tblCodons;";
Then you can execute both query using a single DataReader. When you execute DataReader.ExequteQuery() it will contain two results.the first one has access to the count and the second one has access to actual data.
Here's an example

Categories