Why can't I call OpenConnection() twice in one method? When I call it this error appears:
The connection is already open.
I call it twice in SelectDisPatient() and Count(). See my code at for (int index = 0; index < Count(); index++)
This method SelectDisPatient:
public void SelectDisPatient(FrmVIRGO frm)
{
string query = "SELECT id_pasien FROM tb_patient_information ";
if (this.OpenConnection() == true)
{ //Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dataReader.HasRows)
{
for (int index = 0; index < Count(); index++)
dataReader.Read();
frm.tbName.Text = dataReader[0].ToString();
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
}
}
This Count() method:
public int Count()
{
string query = "SELECT Count(*) FROM tb_patient_information";
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar()+"");
//close Connection
this.CloseConnection();
return Count;
}
else
{
return Count;
}
}
But when I remove (this.OpenConnection() == true) in the Count() method it says I need to close the connection.
Try:
public void SelectDisPatient(FrmVIRGO frm)
{
int count = Count();
string query = "SELECT id_pasien FROM tb_patient_information ";
if (this.OpenConnection() == true)
{ //Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dataReader.HasRows)
{
for (int index = 0; index < count ; index++)
dataReader.Read();
frm.tbName.Text = dataReader[0].ToString();
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
}
}
Related
Everything works fine except the labels[i]. The loop is always writing in htmlLabel1 and never in htmlLabel2 etc.
Why does the iteration doesn't work by labels[i] but at Reader.GetValue(i) just fine?
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
HtmlLabel[] labels = new HtmlLabel[] {
htmlLabel1,
htmlLabel2,
htmlLabel3
};
for (int i = 0; i < Reader.FieldCount; i++)
{
labels[i].Text = Reader.GetValue(i).ToString();
Console.WriteLine(Reader.GetValue(i).ToString());
}
}
connection.Close();
There is only one field so Reader.FieldCount will return 1 every time.
if you want to loop through rows use the following code
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
int i=0;
HtmlLabel[] labels = new HtmlLabel[] {
htmlLabel1,
htmlLabel2,
htmlLabel3
};
while (Reader.Read())
{
//for (int i = 0; i < Reader.FieldCount; i++)
//{
labels[i].Text = Reader[0].ToString();
Console.WriteLine(Reader[0].ToString());
//}
i +=1;
}
connection.Close();
I have this code. When I execute this once, I am able to get the correct list. But when I run this method again, the reader has no data. I was thinking did I forget to close some connection before calling it again, thus leading to the null result
public IEnumerable<List<string>> retreiveList()
{
string query = "SELECT * FROM table1;";
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
List<string> toReturn=new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
toReturn.Add(reader[i].ToString());
yield return toReturn;
}
reader.Close();
}
This is what I want:
A method that is within a class that will return iteratively the values of a certain column. This values will the be added to a combobox when the method is invoked. Here is my attempt:
public string FillCombo()
{
string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
string query = "Select * from categorias";
SqlConnection conn = new SqlConnection(connstring);
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader read;
conn.Open();
read = command.ExecuteReader();
while (read.Read())
{
string combodata = read.GetString(1);
return (combodata);
}
return null;
}
however, when this method is invoked, it only returns the first row into de combobox, not the other values.
It's called yield
http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx
From the manual
public static System.Collections.IEnumerable Power(int number, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * number;
yield return result;
}
}
yield will send a collection of return results from inside a loop after the loop has completed.
You can close data connections using a try/finally block around the loop.
public IEnumerable FillCombo()
{
SqlConnection conn = new SqlConnection(connstring);
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader read;
conn.Open();
read = command.ExecuteReader();
try
{
while (read.Read())
{
yield return read.GetString(1);
}
}
finally
{
read.close();
conn.close();
}
}
A cool and often overlooked feature of C#
Consider using a List of string as an output. The following minor change to your code should help...
public List<string> FillCombo()
{
List<string> comboList = new List<string>();
string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
string query = "Select * from categorias";
SqlConnection conn = new SqlConnection(connstring);
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader read;
conn.Open();
read = command.ExecuteReader();
while (read.Read())
{
string combodata = read.GetString(1);
comboList.Add(combodata);
}
return comboList;
}
Good Luck!
I have quite a number of questions lately about SQL statements in MySQL, but I none have fit my purpose.
I have a class which is where my SQL statements will be saved so that I could use them as methods to keep my code neat. I have already done the Insert, Update, Delete, and Count statements, but I can't seem to find a solution for the SELECT statement
Here are the codes for the other statements:
public void Insert(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public void Update(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = mycon;
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public void Delete(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public int Count(string query)
{
int count = 0;
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
count = int.Parse(cmd.ExecuteScalar() + "");
CloseConnnection();
return count;
}
else
{
return count;
}
}
I am thinking of a SELECT method that would look something like this:
public string[] Select(string query, int colnum)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
MySqlDataReader dr = new MySqlDataReader();
string[] info = new string[colnum];
dr = cmd.ExecuteReader();
while (dr.Read())
{
for (int i = 0; i <= colnum; i++)
{
info[i] = (dr[colnum].ToString());
}
}
}
}
this line is quite fictional info[i] = (dr[colnum].ToString());
since I know It will not function the way I want it to. I am looking for something with a similar logic or something like that that would let me take advantage of the SELECT statements by using methods..
Why dont you use Nhibernate (http://nhforge.org/). Read http://geekswithblogs.net/pariam/archive/2006/07/26/86352.aspx for a tutorial to use nhibernate with mysql
EDIT:
With your code, I am not sure about how concurrency can be handled. But Nhibernate does it for you. Read this
Read this for concurrency concept details
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...