Display mySql table in a label in C# - c#

I'm trying to implement an application combine with mysql database. I want to show table1 like in a terminal view instead of displaying it in a datagrid view. I'm using the code below to connect and display from MySql Database:
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
label1.Text = myReader[0].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
This code only execute the last value of the table. but, I want to display whole table plus I want it to show in a label. So that I can style it like a terminal view.
Any help on this would be great.
Thanks in Advanced!

I think MySqlDataReader.FieldCount Property will be useful.
Try this code:
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
if(label1.Text.Length > 0)
label1.Text += Environment.NewLine;
for(int i=0; i<myReader.FieldCount; i++)
label1.Text += myReader[i].ToString() + " ";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
NOTE: It is recommeded to use using statement for mysqlconnection, mysqldatareader and mysqlcommand.
UPDATE (using StringBuilder as recommended by jmcilhinney):
// Method used to retrieve data from DB
string GetFormattedText()
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
using (MySqlConnection myConn = new MySqlConnection(myConnection))
{
myConn.Open();
using (MySqlCommand command = myConn.CreateCommand())
{
command.CommandText = "Select * FROM database_name.table1";
using (MySqlDataReader myReader = command.ExecuteReader())
{
try
{
StringBuilder sb = new StringBuilder();
while (myReader.Read())
{
if (sb.Length > 0)
sb.Append(Environment.NewLine);
for (int i = 0; i < myReader.FieldCount; i++)
sb.AppendFormat("{0} ", myReader[i]);
}
return sb.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
return string.Empty;
}
Usage:
label1.Text = GetFormattedText();

Related

C# closing mysql connection is not working, mysqli_connect(): (08004/1040): Too many connections

I'm getting this error on phpMyAdmin
mysqli_connect(): (08004/1040): Too many connections
The only script that is using this DB:
public static bool checkIp(string ip)
{
Console.WriteLine("CHECKIP");
try
{
string sql = " SELECT * FROM `Ip tables` ";
MySqlConnection con = new MySqlConnection("host=hostname;user=username;password=password;database=database;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
con.Close();
return false;
}
catch(SqlException exp)
{
throw new InvalidOperationException("Error", exp);
}
}
Does this code close the connection correctly or something is wrong?
EDIT:
I added this block after the catch block
finally
{
if(con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
Any better way to write the code? Would finaly block still run if return is executed?
You should put your query in a using statement like this:
string conString= "host=hostname;user=username;password=password;database=database;"
using (MySqlConnection con = new MySqlConnection(conString))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM `Ip tables`";
using (MySqlDataReader dr = com.ExecuteReader())
{
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
}
}
}
This will automatically close the connection without having to state con.Close()

How to get values of mysql database based on textbox values given in another form

I tried it using C# and MySQL
MySqlCommand command = conn.CreateCommand();
command.CommandText = "select student_name,student_reg_no FROM student WHERE student_id ='" + form2.textBox1.Text + "';";
MySqlDataReader myReader;
try
{
conn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
label1.Text = myReader[0].ToString();
label2.Text = myReader[1].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
not showing the record in the labels and no error message.

SQL Server cannot build connection string to db

I tried the following in SQL Server Management Studio; I can connect and run query, but not from my project
string s = "Server=LAPTOP-7J47C5JA\SQLEXPRESS;Database=Test;Trusted_Connection=True;";
string queryString = "SELECT * from tbclienti";
cn = new SQLConnection(s);
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
cn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
cn.Close();
I posted here whole code what could look like. Try it now.
string s = #"Server=(local)\SQLEXPRESS;Database=Test;Integrated Security=SSPI;";
using(SqlConnection cn = new SqlConnection(s))
{
string queryString = "SELECT * from tbclienti";
try
{
cn.Open();
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
}
catch(Exception ex)
{
// see if error appear
}
finally
{
cn.Close();
}
}

How to Remove Duplicate OUTPUT in SQL?

I have a problem with a ComboBox, its items are being duplicated. How can I prevent this situation? Here is some images:
Here is my code sample used to populate it:
string SelectQuery = "SELECT Part , Model FROM ctautoparts.nissanpart , ctautoparts.nissan ;";
MySqlConnection sqlConn = new MySqlConnection(myConnectionString);
MySqlCommand cmdDatabase = new MySqlCommand(SelectQuery, sqlConn);
MySqlDataReader myReader;
try
{
sqlConn.Open();
myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
// string namethestore = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("model");
// this.carmodel.Text = namethestore;
// string namethestore1 = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("parts");
/// this.carpart.Text = namethestore1;
carmodel.Items.Add(myReader["Model"].ToString());
carpart.Items.Add(myReader["Part"].ToString());
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
Add distinct to your select query, so that the duplicates will be removed
It looks your query is returning duplicated lines. I'd suggest executing them separatedely:
try
{
// POPULATE MODELS
string modelsQuery = "SELECT Model FROM ctautoparts.nissan;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(modelsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carmodel.Items.Add(myReader["Model"].ToString());
}
}
}
// POPULATE PARTS
string partsQuery = "SELECT Part FROM ctautoparts.nissanpart;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(partsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carpart.Items.Add(myReader["Part"].ToString());
}
}
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}

winforms C# using sql server 2008

private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am using this code, but there is a problem if there is no data in my table it will not accept.
So I want to use if no data is present it should take CustomerId as 1
It will be NULL of there are no rows so you can:
"select isnull(max(CustomerId), 1) as Id from CustomerDetails"
You should also look at ExecuteScalar which is designed for a singe result.
Try like this
private void fillcode()
{
try
{
SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
con.Open();
string s = "select max(CustomerId) as Id from CustomerDetails";
SqlCommand cmd = new SqlCommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
int i = Convert.ToInt16(dr["Id"].ToString());
sid.Text = (i + 1).ToString();
}
else
{
sid.Text = "1"
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources