Show databases of MySql server - c#

Does anybody know, how to show databases in C#? I know thats possible by executing a sql command show databases, but i dont know how to configure reader. Anybody please help me.
EDIT: I found a solution:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MySqlConnection con = new MySqlConnection(this.constr);
MySqlCommand cmd = con.CreateCommand();
cmd.CommandText = "show databases";
try
{
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string row = "";
for (int i = 0; i < reader.FieldCount; i++)
row += reader.GetValue(i).ToString();
listBox1.Items.Add(row);
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Number.ToString());
MessageBox.Show(ex.Message);
}
}

string myConnectionString = "SERVER=localhost;UID='root';" + "PASSWORD='root';";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SHOW DATABASES;";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string row = "";
for (int i = 0; i < Reader.FieldCount; i++)
row += Reader.GetValue(i).ToString() + ", ";
comboBox1.Items.Add(row);
}
connection.Close();

SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand com = new SqlCommand ("show databases",conn);
conn.Open();
SqlDataReader reader = com.ExecuteReader();
DataTable dt = new DataTable;
dt.Load(reader);
DataRows[] rows = dt.Rows;
Think you can then view the data rows
That said, if you already have the connection string, there's no reason not to open MSqlServer or whatever and view it from there...

Related

How to save DataGridView multiple row data in to MySQL database in c#

I have multiple row data in a single column. I need to save all data in to a MySQL DB. But it's only saving selected rows data only in DataGridView.
Below is my sample code.
private void button1_Click(object sender, EventArgs e)
{
string price = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price +"');";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = MySQLcmd.ExecuteReader();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Appreciate any help 🙂
Thank you!
One way is to use Foreach loop to get all rows value one by one in DataGridView and then insert them.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = "Connection String";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db1.table1 (price) VALUES (#price", con))
{
cmd.Parameters.AddWithValue("#price", row.Cells["ColumnName"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
If you want to save all rows from your Gridview then loop through it and pick up the column value to save.
Also if you want to save/update to the database, you should use ExecuteNonQuery. Finally, dispose of the objects you're creating and the reason for using.
using (MySqlConnection myConn = new MySqlConnection(MySQLConn))
{
myConn.Open();
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlParameter priceParameter = new MySqlParameter("#price");
MySQLcmd.Parameters.Add(priceParameter);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var price = row.Cells["PRICE_COLUMN_NAME"].Value;
MySQLcmd.Parameters["#price"].Value = price;
MySQLcmd.ExecuteNonQuery();
}
}
Dear mbharanidharan88 and user3501749, Thanks for quick support.
With your sup I fond a new code.
Below is my full working code (for me).
private void button1_Click(object sender, EventArgs e)
{
try
{
string MySQLConn = "datasource=localhost;port=3306;username=root;password=root;";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
myConn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string price = dataGridView1.Rows[i].Cells[3].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price + "');";
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySQLcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If anything wrong let me know 🙂

InvalidOperationException exception while trying to execute an update query

private void button1_Click(object sender, EventArgs e)
{
int f = 1;
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; database = 'C:\Users\Emil Sharier\Documents\testDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
int bal = 0;
string cmdstr = "select * from users where userid='"+ Form1.userid+"';";
cmd.CommandText = cmdstr;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
bal = int.Parse(dr[2].ToString());
int draw = int.Parse(textBox1.Text);
if(draw > bal)
{
MessageBox.Show("Insufficient balance!");
return;
}
else
{
bal -= draw;
cmdstr = "update users set balance='"+bal.ToString()+"' where userid='"+ Form1.userid + "';";
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = con.CreateCommand();
da.UpdateCommand.CommandText = cmdstr;
try
{
da.UpdateCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
f = 0;
}
if (f == 1)
MessageBox.Show("Money withdrawn succesfully!");
else
MessageBox.Show("Enter correct amount!");
}
con.Close();
}
I am getting an "InvalidOperationException" while executing this program. I am not sure what the error is. Please help.
da.UpdateCommand.ExecuteNonQuery() is not getting executed
......
var sqlcmd = new SqlCommand(cmdstr, con);
.....
try
{
sqlcmd.ExecuteNonQuery();
....
Don't use adapter.
And yes. Faster of all try to close connection and open new one for update operation.

C# MySqlConnector next query in the same connection

I have the following code:
string myConnection = "server=localhost;database=test;uid=test;password=test";
string query = "SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlCommand command = new MySqlCommand(query, myConn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
MySqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read()) {
orderNumber = myReader.GetString(1);
myReader.Close();
string queryOrder = "SELECT id_order, id_carrier FROM ps_orders WHERE id_order=28329";
MySqlCommand commandOrder = new MySqlCommand(queryOrder, myConn);
MySqlDataReader myReaderOrder;
myReaderOrder = commandOrder.ExecuteReader();
idCarrier = myReaderOrder.GetString(1);
printDocument1.Print();
}
I have a problem because the second query string queryOrder doesn't work. The query is Ok but variable "idCarrier" doesn't accept any value.
I don't believe you can attach another reader to a connection, when one is already open and processing records. You must retrieve all your records first, i.e. ToList() or Dataset, or use a secondary connection for the second reader.
To make your life easier, consider using Dapper or Linq2Db, two awesome micro-ORMs.
Try it like this:
using(var connection = new MySqlConnection("server=localhost;database=test;uid=test;password=test") {
connection.Open();
int orderNumber = 0;
using (var command = connection.CreateCommand()) {
command.CommandText = #"SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
var reader = command.ExecuteReader();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
if(reader.Read()) {
orderNumber = Convert.ToInt32(reader.GetString(1));
}
}
using(var command = connection.CreateCommand()) {
command.CommandText = string.format(#"SELECT id_order, id_carrier FROM ps_orders WHERE id_order={0}",orderNumber);
var reader = command.ExecuteReader();
if(reader.Read()){
printDocument1.Print();
return reader.GetString(1);
}
}
}

Combobox Showing Old Database Values

I retrived values by the use of SqlCommand and SqlReader from column and stored in List<String> and the added to ComboBox(Type:DropDownList) but Eventhough i have deleted Some of this values from database Combobox is still showing it.
I am clearing items befor allocating by
mycombobox.Items.Clear();
It looks as it is not affected by values I retrive every time when the Form gets Loaded.
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection=new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
foreach(string pname in namesCollection)
cb.Items.Add(pname);
namesCollection.Clear();
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
Thanks in advance.
Use the DataSource property of the Combobox instead of the adding the items one by one. So your code will be something like the following:
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection = new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
//Replace this part...
//foreach(string pname in namesCollection)
//cb.Items.Add(pname);
//With this...
cb.DataSource = namesCollection;
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
There is a similar question here
Hope this helps
Let's say the code to populate the ComboBox is placed in the populate_cb() method
private void populate_cb(){
cb.Items.Clear();
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
cb.Items.Add("Select");
while(rdr1.Read())
{
cb.Items.Add(rdr1[0].ToString());
}
cb.SelectedIndex =0;
con1.Close();
}
catch(Exception ex){
// handle exception
}
}//end of populate_cb()
Call populate_cb() method form form_load() and
Call from the place after the deletion process
You need to make sure your deletion process really deletes the records from database!

Populating ComboBox with Data

I want to display the items in my database inside the combo box after the radio option is been selected. when i tried this nothing was displayed in the combo box. please kindly help
private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
Your try block should resemble the following:
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
//Put some data in the datatable!!
using(OleDbDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
You need to fill your DataTable with data!
You might also consider the following:
using(OleDbDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
This way you don't even need to use a DataTable; this is a more efficient approach for large sets of data.
As an aside, you may wish to consider using Using:
using(OleDbConnection connect = db.dbConnect())
{
try
{
connect.Open();
//MessageBox.Show("Opened");
using(OleDbCommand command = new OleDbCommand())
{
command.Connection = connect;
command.CommandText = "SELECT * FROM Categories";
using(IDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("An erorr occured:" + ex);
}
}
This will ensure your connection, command and reader objects are disposed. This is not appropriate if you intend to hold onto an instance of your connection however as it will be closed AND disposed as soon as your code leaves the using statement.
There is missing filling DataTable dt with datas, which are returned by your sql command.
try with this code - in your sample you don't bind your table with data, you create new instance of table.
$ private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
cmbDisplay.Items.Add(myReader["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
I can't believe this. :D
When are you exactly filling the DataTable with data from DB?
There is nothing in between
DataTable dt = new DataTable();
and
for (int i = 0; i < dt.Rows.Count; i++)
you can fill combobox with Datatable :
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from Books",con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = dt;
You are not filling data in Dataset before attaching try this
if(radio.checked)
{
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataAdapter db = new OleDbDataAdapter();
DataSet ds = new DataSet();
db.SelectCommand = command;
db.Fill(ds);
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
cmbDisplay.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
cmDisplay.DataBind();
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}

Categories