How to delay my program while reading from a database C# - c#

I have a mess with trying to read line by line from a MS Access database and display it on the screen when between every display there are a few seconds of sleeping.
I am using System.Threading as you can see but it seems the sleeping is happening before the program displays the records and when the sleeping is over only the last record is displayed without displaying the previous.
Here is my code, I will really appreciate any help!
private void com_start_Click(object sender, EventArgs e)
{
try
{
string ConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\MyBrainWash\Englishdb.accdb;";
OleDbConnection Con = new OleDbConnection(ConString);
Con.Open();
check_connection.Text = "succeeded";
OleDbCommand command = new OleDbCommand();
command.Connection = Con;
command.CommandText = "Select * From words";
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
Thread.Sleep(30000);
}
}
reader.Close();
Con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}

UI controls lab_word and lab_definition.Text will be updated after whole com_start_Click method completes.
That is why you see that only last row have been shown.
You need "release" UI thread after reading every row for 3 seconds for updating UI controls with new values.
I think async/await approach suits very good this purpose.
Mark button click with async keyword.
private async void com_start_Click(object sender, EventArgs e)
{
string ConString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\MyBrainWash\Englishdb.accdb;";
using (var Con = new OleDbConnection(ConString))
{
Con.Open();
check_connection.Text = "successed";
using (var command = new OleDbCommand())
{
command.Connection = Con;
command.CommandText = "Select * From words";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
await Task.Delay(30000);
}
}
}
}
}
You can also use asynchronous methods of OleDbConnection, OleDbCommand and OleDbReader
private async void com_start_Click(object sender, EventArgs e)
{
string ConString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\MyBrainWash\Englishdb.accdb;";
using (var Con = new OleDbConnection(ConString))
{
await Con.OpenAsync();
check_connection.Text = "successed";
using (var command = new OleDbCommand())
{
command.Connection = Con;
command.CommandText = "Select * From words";
using (var reader = await command.ExecuteReader())
{
while (await reader.ReadAsync())
{
lab_word.Text = reader["word"].ToString();
lab_definition.Text = reader["definition"].ToString();
await Task.Delay(30000);
}
}
}
}
}

Related

How to view data from a database in cmd

Good morning, I'm doing a job where I have to show some information from a database in cmd, I search the internet and only find in Tables DataGrid do not understand how I will do, I have the following code:
public class atm
{
public static void Main()
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;";
cnn = new SqlConnection(connectionString);
try
{
using (SqlCommand cmd = cnn.CreateCommand())
{
cnn.Open();
Console.WriteLine("Is working");
var sqlQuery = "SELECT FirstName FROM tblATM";
using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, cnn))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
Console.WriteLine(dt);
}
}
}
}
catch (SqlException erro)
{
Console.WriteLine("Is not working" + erro);
}
finally
{
cnn.Close();
}
}
}
When I open it says it's working, then I think the connection is working but it doesn't show the database data I'm asking for. If anyone knows how to help me, i'd appreciate it.
A DataTable is overkill, consider the following to loop through the records.
internal class Program
{
static void Main(string[] args)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName FROM tblATM" })
{
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
}
Console.ReadLine();
}
}
With last name
using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName,LastName FROM tblATM" })
{
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{reader.GetString(0)} {reader.GetString(1)}");
}
}
}
You can use dapper to connect and query data from a database connection.
The below link is the official documentation of dapper
https://www.learndapper.com/ here you can find sample code also.

how do I avoid the startup delay when I connect to a MySQL database using c# system.data.mysqlclient visual-studio on mac

Is there a way to force sql connection when the connection is open.. For the first time I wait 20 seconds to display the data.. after that everything is ok..
I use system.data.mysqlclient library for connect to cloud sql.
The code:
void Btn_GetPlaces(System.Object sender, System.EventArgs e)
{
try
{
string cs = #"server=192.168.0.1,3306;userid=Alex;password=Alex123;database=DBMeteo";
var connection = new MySqlConnection(cs);
connection.Open();
LabelSQL.Text = "Connection has beed sucsessfully..";
var cmd = new MySqlCommand();
cmd.Connection = connection;
MySqlCommand command = new MySqlCommand($"CALL nearest3({GlobalLat}, {GlobalLong}, 1)", connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// access your record colums by using reader
LabelPlace.Text = (reader[0]).ToString();
LabelDist.Text = (reader[1]).ToString();
LabelCode.Text = (reader[2]).ToString();
}
}
connection.Close();
}
catch (Exception ex)
{
LabelSQL.Text = (ex.ToString());
}
}

Output Not Displaying in TextBox in C#

I am new to C# and I have connected it with Oracle11g and using Visual Studio 2013 as a tool. I am trying to display a 'name ' that is being returned by a query to a textbox but it is neither displaying an Error Message nor displaying the Output. Pleases help me to resolve this problem. Thanks... here is my code..
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr.GetString(0);
conn.Dispose();
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
after setting textBox1.Text = dr.GetString(0);
it is giving me the attached exception.
Array indexes start at index zero, not 1. The returned string (if any) is at
textBox1.Text = dr.GetString(0);
A more correct way to write your code is the following
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
// Use the using statements around disposable objects....
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
// These two parameters could be passed directly in the
// OracleCommand constructor....
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
// Again using statement around disposable objects
using(OracleDataReader dr = cmd.ExecuteReader())
{
// Check if you have a record or not
if(dr.Read())
textBox1.Text = dr.GetString(0);
}
}
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
And if your code is supposed to return just a single record with a single column then you can use the more performant ExecuteScalar without building an OracleDataReader
// Again using statement around disposable objects
object result = cmd.ExecuteScalar();
if(result != null)
textBox1.Text = result.ToString();

SqliteDataReader doesn't work in C#?

I have some data stored in a SQLite database which I want to display on a webpage in C#. I searched for the right thing to do but only found console.writeline, and beside that the SqliteDataReader function is not working. This is my code:
protected void Page_Load(object sender, EventArgs e)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db"))
{
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
command.Connection = conn;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
string test = ("Name: " + reader["name"] + "\tScore: " + reader["score"]);
command.ExecuteNonQuery();
conn.Close();
}
}
What should I do?
Thanks in advance,
Elias
It seems that you've forgot to put the actual query to perform:
command.CommandText = "...";
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
//TODO: do not hardcode connection string, move it to settings
string connectionString =
#"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";
// var for simplicity
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();
using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;
//TODO: put the right SQL to perform here
command.CommandText =
#"select name,
score
from MyTable";
using (var reader = command.ExecuteReader()) {
string test = "";
// do we have any data to read?
//DONE: try not building string but using formatting (or string interpolation)
if (reader.Read())
test = $"Name: {reader["name"]}\tScore: {reader["score"]}";
//TODO: so you've got "test" string; do what you want with it
}
}
//DONE: you don't want command.ExecuteNonQuery(), but command.ExecuteReader()
//DONE: you don't want conn.Close() - "using" will do it for you
}
}

Jut get as result: System.Data.SqlClient.SqlDataReader

Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}
You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}
before execute "executeReader()" then you must read to get results.
Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}
you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...

Categories