Getting MySQL record count with C# - c#

I would like to know how can I get record count of a query with C#.
Here is the code that I use..
MySqlDataReader recordset = null;
query = new MySqlCommand("SELECT * FROM test ORDER BY type_ID ASC", this.conn);
recordset = query.ExecuteReader();
while (recordset.Read())
{
result.Add(recordset["type_ID"].ToString());
}
return result;

I was using a SELECT COUNT(*) and expected an int to be returned. You may need this to get a usable value:
mysqlint = int.Parse(query.ExecuteScalar().ToString());

A couple of things...
The SQL statement you would use is:
SELECT COUNT(*) FROM test
However, when using the MySQL Connector/Net to connect to MySQL through C# there is some care to be given when handling query results.
For example, as cited in this question and on Microsoft Connect int.Parse("0") equivalently known as Int32.Parse("0") can throw a FormatException on some machines.
I have found that Convert.ToInt32 handles this case nicely.
So your code will be something like this:
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM test", conn))
{
int count = Convert.ToInt32(cmd.ExecuteScalar());
return count;
}
}
Remember to make use of using statements in order to ensure that the MySQL objects get disposed of properly.

You're adding a new element in result for each row. Depending on the type of result you should be able to do something like result.Count after the while loop completes.

You could run another query first to get the count :
query = new MySqlCommand("SELECT count(*) as theCount FROM test ORDER BY type_ID ASC", this.conn);
but in truth, you are probably best changing the problem so you wont need the count until after you have populated the list.

Related

how to display database value in console in c#

How to display the unitfunction value from mysql database and my query is below ,i don't know its right or wrong.
Help me out.
string fundev = "select unitfunctioncode from channels where channel_no = " + Channelid;
MySqlCommand getfun = new MySqlCommand(fundev, Connection1);
Console.WriteLine(getfun);
MAKE ENTITY CONTEXT FIRST:
YourEntity db= new YourEntity();
LINQ:
Console.Write(db.channels.Where(x=>x.channel_no == Channelid).Select(y=>y.unitfunctioncode));
This is modal first approach create modal from database and call this linq in controller
I'm not sure about the specifics of MySqlCommand, but I would expect to see an execute on your getfun object.
I would do something like this:
MySqlDataReader rdr = getfun.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
rdr.Close();
This takes into account multiple rows returned. You can omit the while loop if you're sure you will have a single row returned.

How to get data from multiple SELECT statements and store it in the DataSet

I am trying to execute multiple SELECT statements, such as,
DataSet ds = new DataSet();
string sql = #"SELECT * FROM CUSTOMERS;
SELECT * FROM CUSTOMERS WHERE AGE > 40;";
using (FbConnection connection = new FbConnection(ConectionString))
{
try
{
using (FbCommand cmd = connection.CreateCommand())
using (FbDataAdapter sda = new FbDataAdapter(cmd))
{
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
connection.Open();
sda.Fill(ds);
}
}
catch (FbException e)
{
Error = e.Message;
}
finally
{
connection.Close();
}
}
return ds;
The above code works great for one SELECT statement, but it throws an exception when there are multiple SELECT statements.
Dynamic SQL Error
SQL error code = -104
Token unknown - line 2, column 1
SELECT
I have tried the FbBatchExecution as well but I don't know how to get the returned data from it. It works well when using multiple INSERT or DELETE statements.
You have to build ONE query out of those two using SQL UNION operator
https://en.wikipedia.org/wiki/Set_operations_(SQL)#UNION_operator
https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-select.html#fblangref25-dml-select-union
Note how these your queries fetch the same rows: the first query has all the rows of the second plus some more
SELECT * FROM CUSTOMERS;
SELECT * FROM CUSTOMERS WHERE AGE > 40;
Basically you have two ways to link them together
SELECT * FROM CUSTOMERS
UNION ALL
SELECT * FROM CUSTOMERS WHERE AGE > 40
and
SELECT * FROM CUSTOMERS
UNION DISTINCT
SELECT * FROM CUSTOMERS WHERE AGE > 40
The first option would just link one query after another, without caring what the data they have brought. And unless you add ORDER BY clause it also would most probably keep the order of rows produced by sequential queries, just because it is easier to do so. However there is no warranty on that in neither SQL standard nor Firebird documentation, in other words that is purely "implementation detail" and there is some chance that in future rows would get reordered interleaving the queries even with UNION ALL w/o ORDER BY link (for example if the subqueries would be spawn into different processors for parallelization).
The second option would sort the outputs in temporary buffers and exclude duplicates, which would mean more working time for the server and more volume in memory and/or disk used for that temporary buffers and sorting, but would ensure you do not have duplicates in the rows (which means your specific queries would have then the same set of data as the first query alone).
Contrary to SQL Server, Firebird doesn't support execution of multiple statements in a single execute, nor can a single execute produce multiple result sets. If you want to execute multiple statements, you will need to execute them individually.
You also can't use FbBatchExecution because that is for executing inserts, updates, deletes, etc (statements that don't produce a result set).
I dont know FbConnection provider, but if implement IDbConnection, so you can maybe use Dapper and then your problem solve this:
https://dapper-tutorial.net/querymultiple
string sql = "SELECT * FROM Invoice WHERE InvoiceID = #InvoiceID; SELECT * FROM InvoiceItem WHERE InvoiceID = #InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
using (var multi = connection.QueryMultiple(sql, new {InvoiceID = 1}))
{
var invoice = multi.Read<Invoice>().First();
var invoiceItems = multi.Read<InvoiceItem>().ToList();
}
}
Try this:
using (SqlConnection sql = new SqlConnection(key))
{
try
{
sql.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = #"SELECT * FROM CUSTOMERS;
SELECT * FROM CUSTOMERS WHERE AGE > 40;";
cmd.Connection = sql;
var dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//First query data
}
if (dr.NextResult())
{
if (dr.HasRows)
{
while (dr.Read())
{
//Second Query Data
}
}
}
}
}
catch (FbException e)
{
Error = e.Message;
}
finally
{
sql .Close();
}
}

select query does not work with parameters using Parameters.AddWithValue

The following query in C# doesn't work, but I can't see the problem:
string Getquery = "select * from user_tbl where emp_id=#emp_id and birthdate=#birthdate";
cmdR.Parameters.AddWithValue("#emp_id", userValidate.emp_id);
cmdR.Parameters.AddWithValue("#birthdate", userValidate.birthdate);
OdbcCommand cmdR = new OdbcCommand(Getquery, conn);
OdbcDataReader Reader = cmdR.ExecuteReader();
Reader.HasRows returns no result but when I query it to my database I got data.
I'll assume your code is actually not quite as presented, given that it wouldn't currently compile - you're using cmdR before you declare it.
First, you're trying to use named parameters, and according to the documentation of OdbcCommand.Parameters, that isn't supported:
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder.
Additionally, I would personally avoid using AddWithValue anyway - I would use something like:
string sql = "select * from user_tbl where emp_id = ? and birthdate = ?";
using (var connection = new OdbcConnection(...))
{
connection.Open();
using (var command = new OdbcCommand(sql, connection))
{
command.Parameters.Add("#emp_id", OdbcType.Int).Value = userValidate.EmployeeId;
command.Parameters.Add("#birthdate", OdbcType.Date).Value = userValidate.BirthDate;
using (var reader = command.ExecuteReader())
{
// Use the reader here
}
}
}
This example uses names following .NET naming conventions, and demonstrates properly disposing of resources... as well as fixing the parameter issue.
I do think it's slightly unfortunate that you have to provide a name for the parameter when adding it to the command even though you can't use it in the query, but such is life.
Use like this:
string Getquery = "select * from user_tbl where emp_id=? and birthdate=?";
cmdR.Parameters.AddWithValue("#emp_id", userValidate.emp_id);
cmdR.Parameters.AddWithValue("#birthdate", userValidate.birthdate);
OdbcCommand cmdR = new OdbcCommand(Getquery, conn);
OdbcDataReader Reader = cmdR.ExecuteReader();
while(Reader.Read())
{
//Do something;
}
I know this thread is old, but I wanted to share my solution for anyone else coming up on this.
I was having issues with the typical method that Jon posted. I have used it before, but for some reason with this new string I had it was not wanting to actually place the parameter correctly and was causing the reader to not work.
I ended up doing something like this instead, since in the end we are just replacing parts of a string.
string sql = "select * from user_tbl where emp_id = "+ var1 +" and birthdate = "+
var2""
OdbcCommand command = new OdbcCommand(sql);
This was easier for me to get to work. Be warned though, I am not sure if it has any specific drawbacks when compare to using the command parameter method.

How to check if mysql table is empty?

How to check if my table is empty from C#?
I have something like:
public MySqlConnection con;
public MySqlCommand cmd;
con = new MySqlConnection(GetConnectionString());
con.Open();
cmd = new MySqlCommand("SELECT * FROM data;", con);
Or I don't need to call SELECT statement?
You can use COUNT(*) with no WHERE close and see if exactly how many rows exist with the result.
Or you can do a SELECT (id) FROM tablename with no WHERE clause and if no rows are returned then the table is empty.
I'll give you an example in C# good luck
public bool checkEmptyTable(){
try
{
MySql.Data.MySqlClient.MySqlCommand com = new MySql.Data.MySqlClient.MySqlCommand();
conn = new MySql.Data.MySqlClient.MySqlConnection("YOUR CONNECTION");
com.Connection = conn;
com.CommandText = "SELECT COUNT(*) from data";
int result = int.Parse(com.ExecuteScalar().ToString());
return result == 0; // if result equals zero, then the table is empty
}
finally
{
conn.Close();
}
}
If 'data' might be a big table you would be better with this (where pkdata is your primary key field)
SELECT COUNT(*) FROM data WHERE pkdata = (SELECT pkdata FROM data LIMIT 1);
This will run very quickly whether you have 0 rows in 'data' or millions of rows. Using SELECT with no WHERE or ORDER BY means it just pulls the first row available, LIMIT 1 stops it getting more than 1.
Maybe something to look for if you have a program that ran very quickly six months ago but now runs like a dog in treacle!
SELECT COUNT(*)
FROM table
WHERE `col_name` IS NOT NULL

Getting the Last Insert ID with SQLite.NET in C#

I have a simple problem with a not so simple solution... I am currently inserting some data into a database like this:
kompenzacijeDataSet.KompenzacijeRow kompenzacija = kompenzacijeDataSet.Kompenzacije.NewKompenzacijeRow();
kompenzacija.Datum = DateTime.Now;
kompenzacija.PodjetjeID = stranka.id;
kompenzacija.Znesek = Decimal.Parse(tbZnesek.Text);
kompenzacijeDataSet.Kompenzacije.Rows.Add(kompenzacija);
kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter kompTA = new kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter();
kompTA.Update(this.kompenzacijeDataSet.Kompenzacije);
this.currentKompenzacijaID = LastInsertID(kompTA.Connection);
The last line is important. Why do I supply a connection? Well there is a SQLite function called last_insert_rowid() that you can call and get the last insert ID. Problem is it is bound to a connection and .NET seems to be reopening and closing connections for every dataset operation. I thought getting the connection from a table adapter would change things. But it doesn't.
Would anyone know how to solve this? Maybe where to get a constant connection from? Or maybe something more elegant?
Thank you.
EDIT:
This is also a problem with transactions, I would need the same connection if I would want to use transactions, so that is also a problem...
Using C# (.net 4.0) with SQLite, the SQLiteConnection class has a property LastInsertRowId that equals the Primary Integer Key of the most recently inserted (or updated) element.
The rowID is returned if the table doesn't have a primary integer key (in this case the rowID is column is automatically created).
See https://www.sqlite.org/c3ref/last_insert_rowid.html for more.
As for wrapping multiple commands in a single transaction, any commands entered after the transaction begins and before it is committed are part of one transaction.
long rowID;
using (SQLiteConnection con = new SQLiteConnection([datasource])
{
SQLiteTransaction transaction = null;
transaction = con.BeginTransaction();
... [execute insert statement]
rowID = con.LastInsertRowId;
transaction.Commit()
}
select last_insert_rowid();
And you will need to execute it as a scalar query.
string sql = #"select last_insert_rowid()";
long lastId = (long)command.ExecuteScalar(sql); // Need to type-cast since `ExecuteScalar` returns an object.
last_insert_rowid() is part of the solution. It returns a row number, not the actual ID.
cmd = CNN.CreateCommand();
cmd.CommandText = "SELECT last_insert_rowid()";
object i = cmd.ExecuteScalar();
cmd.CommandText = "SELECT " + ID_Name + " FROM " + TableName + " WHERE rowid=" + i.ToString();
i = cmd.ExecuteScalar();
I'm using Microsoft.Data.Sqlite package and I do not see a LastInsertRowId property. But you don't have to create a second trip to database to get the last id. Instead, combine both sql statements into a single string.
string sql = #"
insert into MyTable values (null, #name);
select last_insert_rowid();";
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = sql;
cmd.Parameters.Add("#name", SqliteType.Text).Value = "John";
int lastId = Convert.ToInt32(cmd.ExecuteScalar());
}
There seems to be answers to both Microsoft's reference and SQLite's reference and that is the reason some people are getting LastInsertRowId property to work and others aren't.
Personally I don't use an PK as it's just an alias for the rowid column. Using the rowid is around twice as fast as one that you create. If I have a TEXT column for a PK I still use rowid and just make the text column unique. (for SQLite 3 only. You need your own for v1 & v2 as vacuum will alter rowid numbers)
That said, the way to get the information from a record in the last insert is the code below. Since the function does a left join to itself I LIMIT it to 1 just for speed, even if you don't there will only be 1 record from the main SELECT statement.
SELECT my_primary_key_column FROM my_table
WHERE rowid in (SELECT last_insert_rowid() LIMIT 1);
The SQLiteConnection object has a property for that, so there is not need for additional query.
After INSERT you just my use LastInsertRowId property of your SQLiteConnection object that was used for INSERT command.
Type of LastInsertRowId property is Int64.
Off course, as you already now, for auto increment to work the primary key on table must be set to be AUTOINCREMENT field, which is another topic.
database = new SQLiteConnection(databasePath);
public int GetLastInsertId()
{
return (int)SQLite3.LastInsertRowid(database.Handle);
}
# How about just running 2x SQL statements together using Execute Scalar?
# Person is a object that has an Id and Name property
var connString = LoadConnectionString(); // get connection string
using (var conn = new SQLiteConnection(connString)) // connect to sqlite
{
// insert new record and get Id of inserted record
var sql = #"INSERT INTO People (Name) VALUES (#Name);
SELECT Id FROM People
ORDER BY Id DESC";
var lastId = conn.ExecuteScalar(sql, person);
}
In EF Core 5 you can get ID in the object itself without using any "last inserted".
For example:
var r = new SomeData() { Name = "New Row", ...};
dbContext.Add(r);
dbContext.SaveChanges();
Console.WriteLine(r.ID);
you would get new ID without thinking of using correct connection or thread-safety etc.
If you're using the Microsoft.Data.Sqlite package, it doesn't include a LastInsertRowId property in the SqliteConnection class, but you can still call the last_insert_rowid function by using the underlying SQLitePCL library. Here's an extension method:
using Microsoft.Data.Sqlite;
using SQLitePCL;
public static long GetLastInsertRowId(this SqliteConnection connection)
{
var handle = connection.Handle ?? throw new NullReferenceException("The connection is not open.");
return raw.sqlite3_last_insert_rowid(handle);
}

Categories

Resources