C# Excel result comparation - c#

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

Related

UWP Custom Sqlite Query to JSON

I'm searching for a way to Execute Custom SQL Queries and to provide the result in JSON. Normally you have to provide a Class for the Query result e.g.
var query = dbConn.Query<ClassTypes>("Select a as key, b as value FROM table WHERE id = ?", new object[] { ObjectID });
But in my case, I don't know the SQL Statement, because its provided by an external JavaScript from a Webview.
This Webview might ask my application to Execute
Select a.col1 as foo,b.col1, a.col2 FROM table1 a INNER JOIN table2 b ON a.id=b.aid
And wants me to return:
foo:xxx
col2:yyy
Which columns are "asked" by the SQL Statement is completely free, or which aliases are used, I just want to execute the Statement an return key value pairs with the aliases or column names and the values in a JSON (for each row).
So I'm not able to prepare a custom Class for the Query, because I don't know the format of the SQL Query.
Does anyone have an idea?
I just want to execute the Statement an return key value pairs with the aliases or column names and the values in a JSON (for each row).
For your scenario, You could use SqlDataReader to approach, SqlDataReader contains GetName method that could use to get the column name as key, and it also contains GetSqlValue method that could retrieve column's value. If you can't confirm the field count, you could also use FieldCount to get current reader 's field counts
For example
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetProductsQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
var list = new List<Dictionary<string, object>>();
while (reader.Read())
{
var dict = new Dictionary<string, object>();
var i = 0;
do
{
var key = reader.GetName(i);
var value = reader.GetSqlValue(i);
dict.Add(key, value);
i++;
} while (i < reader.FieldCount);
list.Add(dict);
}
}
}
}
}
For more detail please refer this document.

How to count all rows in a data table 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.

How to fetch only some rows from a SqlDataReader?

i'm fetching values from a table with datareader like this:
string query = #"SELECT XMLConfig, Enable FROM TableCfg";
using (SqlConnection cnction = new SqlConnection(cnnstr))
{
cnction.Open();
using (SqlCommand sqlCmd = new SqlCommand(query, cnction))
{
SqlDataReader dtRead = sqlCmd.ExecuteReader();
while (dtRead.Read())
{
xmlConf = dtRead.GetString(0);
enabl = dtRead.GetString(1);
}
dtRead.Close();
}
}
The Enable field is a boolean(True/False). Is there a way to fetch only the rows, where field enable="True"?
I tried using LINQ, but i'm new to this and i must be doing something wrong.
using (SqlCommand sqlCmd = new SqlCommand(query, cnction))
{
SqlDataReader dtRead = sqlCmd.ExecuteReader();
var ob =(from IDataRecord r in sqlCmd.ExecuteReader()
where r.GetString(3).ToString() == "True"
select "Enable");
}
Help me please.
Best Regards.
You should really do as much filtering as possible at the database side rather than client-side:
string query = "SELECT XMLConfig FROM TableCfg WHERE Enable = True";
Notice how now you don't even need to fetch Enable, as you already know it will be True for all the matching rows.
You should also consider using LINQ to SQL or Entity Framework rather than the rather low-level stack you're currently using. It's not always appropriate, but it does make things cleaner where it's suitable.

What is C# equivalent of PHP's mysql_fetch_array function?

I am learning C#/ASP.NET and I am wondering what the C# equivalent of the following PHP code is?
I know the userid, and I want to fetch the rows from this table into the array of the variable "row", so I then can use it as "row['name']" and "row['email'].
$result = mysql_query("SELECT email, name FROM mytable WHERE id=7");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("Email: %s Name: %s", $row["email"], $row["name"]);
}
Thanks.
I'm not sure if this is the same as mysql_fetch_array but i assume that.
You can use IDBCommmand.ExecuteReader to create an IDataReader and use that to fill an Object[] with all fields of the row.
For example (using SQL-Server):
// use using statements to ensure that connections are disposed/closed (all implementing IDisposable)
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using (var cmd = new SqlCommand("SELECT email, name FROM mytable WHERE id=#id", con))
{
cmd.Parameters.AddWithValue("#id", ID); // use parameters to avoid sql-injection
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var fields = new object[reader.FieldCount];
// following fills an object[] with all fields of the current line,
// is this similar to mysql_fetch_array?
int count = reader.GetValues(fields);
}
}
}
Edit:
I don't mean to make it as similar as possible, but how would I go about getting the same end result (a variable with the results) in C#
That's a matter of taste. You could use some kind of ORM like Enity-Framework, NHibernate, LINQ-To-SQL or Stackoverflow's Micro-ORM Dapper.NET(what i'm using currently) or plain ADO.NET (as shown above).
You can use a custom class that you fill manually with a DataReader or a DataTable which schema is loaded automatically.
For example (here using MySQL):
DataTable tblEmail = new DataTable();
using (var con = new MySqlConnection(Properties.Settings.Default.MySQL))
using (var da = new MySqlDataAdapter("SELECT Email, Name FROM Email WHERE id=#id", con))
{
da.SelectCommand.Parameters.AddWithValue("#id", ID);
da.Fill(tblEmail);
}
if (tblEmail.Rows.Count == 1)
{
DataRow row = tblEmail.Rows[0];
String email = row.Field<String>("Email");
String name = row.Field<String>("Name");
}
As you can see, there are many ways in .NET. I have shown just two with ADO.NET.
There's no true equivalent. Having been a PHP developer in the past, I'd say the closest thing is to use a data adapter and fill a data table. Here's a reference to DbDataAdapter.Fill.
I'm not sure about the MySql driver but if you're using Sql Server here's some code to get you started:
using (var connection = new SqlConnection(connectionString))
{
var table = new DataTable("tbl_objects");
var adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT * FROM tbl_name", connection);
adapter.Fill(table);
}
Then, you can iterate over the rows in the table:
foreach(var row in table)
{
Console.WriteLine("{0}", row["ColumnName"]);
}
You could loop through your result with a foreach loop as follows:
foreach(var row in result)
{
console.writeline("Email:" + row.Email, "Name:", row.Name);
}
Is that the sort of thing you were looking for?
EDIT
In fact i have just seen you only have one result.
Then you can skip the foreach loop altogether
You need a connection to a database.
Assuming you are using mysql and an odbc connection.
var connectionString = "DRIVER={MySQL ODBC 3.51 Driver};" +
"SERVER=localhost;" +
"DATABASE=test;" +
"UID=venu;" +
"PASSWORD=venu;" +
"OPTION=3");
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcCommand command = new OdbcCommand("SELECT email, name FROM mytable WHERE id=7", connection);
connection.Open();
// Execute the DataReader and access the data.
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//do stuff with the data here row by row the reader is a cursor
}
// Call Close when done reading.
reader.Close();
alternately you could use an odbcdataadapter and a datatable if you wanted all the results in a table you could use like an array.
The closest equivalent in .net would be something like this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
var foo = MySqlHelper.ExecuteDataRow("Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;", "select * from foo");
Console.WriteLine(foo["Column"]);
}
}
}
I assume you are using the MySql Data Connector http://dev.mysql.com/downloads/connector/net/
Do note there are better ways available in .net to connect to databases, but I think for a line by line, this is about as close to the PHP as you can get.

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

Categories