How to read specific column and cell in mysql in c#? - c#

I use ExecuteReader to select all (SELECT*) for all field like this
string query = "SELECT* 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();
while (dataReader.Read())
{ ... }
but I only want to select in specific column and cell like in red square.. like this picture

You can get the specific column inside the while clause.
while (dataReader.Read())
{
var _column = dataReader["Nama_Kategori"];
}

Consider using
string query = "SELECT column 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();
if (dataReader.Read())
{
dataReader.ExecuteScalar();
}
}
or use dataReader["columnName"]

You can use ExecuteScalar() of MySqlCommand method to retieve single value
MySqlCommand myCommand = new MySqlCommand("SELECT Nama_Kategori FROM tb_patient_information WHERE Id_kategori = 'KI-02'", myConnection);
myCommand.Connection.Open();
myCommand.ExecuteScalar();
myConnection.Close();

SQL Query
If you want only third row data then try the below query :
Select * from (Select row_number() over (order by subssn) as rownum, * FROM
tb_patient_information)result Where rownum = 3
-This Query return the 3rd row on Result Set
In DataReader
while (dataReader.Read())
{
string Id = dataReader["Id_kategori"].ToString();
string Name = dataReader["Nama_Kategori"].ToString();
}
OR
IF You Say I only use Select * from tb_patient_information and i need 3rd row result Then try like below
int count=1;
while (dataReader.Read())
{
if(count == 3)
{
string Id = dataReader["Id_kategori"].ToString();
string Name = dataReader["Nama_Kategori"].ToString();
}
count ++;
}

Related

how two get data from 2 different table c#

I have two table.I need to get calorificValue from the food table and daily_gained from the calorie_tracker table to then make some calculations.I've written this code, I know it not efficent. It retrieves daily_gained but failed to get calorificValue.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
while (rd.Read()) // while the reader can read
{
if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
{
burned += int.Parse(rd["daily_gained"].ToString());
}
}
}
cmd2.Connection.Close();
cmd.Connection.Open();
MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (rd2.HasRows) // if entered username and password have data
{
while (rd2.Read()) // while the reader can read
{
if (rd2["name"].ToString() == s)
{
burned += int.Parse(rd2["calorificValue"].ToString());
}
}
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=#sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("#sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);
dataGridView1.DataSource = tablo;
cnn.Close();
Why don't you just use the scalar function SUM and let the database do its job instead of writing a lot of code?
int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = #"SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
Not visible from your code, but also the connection should be created inside a using statement (very important with MySql that is very restrictive with simultaneous open connections)
We could also use a different approach putting the two commands together and separating them with a semicolon. This is called batch commands and they are both executed with just one trip to the database. Of course we need to fallback using the MySqlDataReader to get the two results passing from the first one to the second one using the NextResult() method (see here MSDN for Sql Server)
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name;
SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
cnn.Open();
using(MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if(reader.Read()) burned += Convert.ToInt32(reader[0]);
// if there is a second resultset, go there
if(reader.NextResult())
if(reader.Read())
burned += Convert.ToInt32(reader[0]);
}
}
Your issues could be around closing a connection and then trying to open it again. Either way it's fairly inefficient to be closing and opening connections.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
cnn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) // if entered username and password have data
{
while (rd.Read()) // while the reader can read
{
burned += int.Parse(rd["calorificValue"].ToString());
}
}
burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();

Get entire table - MySQL error

Working with C# and MySQL here (Visual Studio 12 and MySQL workbench 6.1).
I'm trying to get the entire table into a list.
This is what I have so far:
List<Object> arrList = new List<Object>();
string str = #"server=localhost;database=test;userid=root;password=asd;";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
arrList.Add(reader["* "]);
}
When I pass SELECT * FROM emp; for query and try to get a toString of arrList, I get an indexOutOfBounds exception. (My table emp has 1 record in it.)
Thanks!
Edit: I'm trying to get the entire table (sequentially) into a list. Is this the right approach?
Edit 2: What if we don't know the number of columns in the table?
Change to:
while (reader.Read())
{
arrList.Add(reader["myColumnTitle"].ToString());
}
cause "* " isn't a valis columnname. alternative you can use an index
arrList.Add(reader[0].ToString());
for each Column:
List arrList = new List();
string str = #"server=localhost;database=test;userid=root;password=asd;";
string query = "SELECT * FROM emp";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
var value = reader[i];
arrList.Add(Convert.ToString(value))
}
}
reader.Read() read your results row by row. That means inside this while statement, you need to read all columns of your query.
When you write "* ", your reader looks for a column named * which you don't have. MySqlDataReader can't understand to read all columns when you write * as you can in an sql query.
This should work.
while (reader.Read())
{
arrList.Add((string)reader[0]);
arrList.Add((string)reader[1]);
}
If you really don't know how many fields that your MySqlDataReader has, you can use SqlDataReader.FieldCount property.
Gets the number of columns in the current row.
So you code can be like;
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
Also use using statement to dispose your database connections and objects like;
using(MySqlConnection con = new MySqlConnection(str))
using(MySqlCommand cmd = con.CreateCommand())
{
...
...
using(MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
}
}

How to show number of rows return in select statement in asp.net

I am fetching records of users and binding it to gridview. I want to show the number of results returned like "15 results found". I used RecordsAffected but I think it wont work with select statement. Any alternate way?
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name, city, number where age between " + from.Text + "AND " + to.Text;
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
reader.Close();
usersgrid.DataSource = cmd.ExecuteReader();
usersgrid.DataBind();
con.Close();
}
else
{
result.Visible = true;
}
}
}
Now I want to show number of rows returned on a label.
int affectedRows = cmd.ExecuteNonQuery();
that would work for you insted of cmd.ExecuteReader();
another alternative will be to get rowcount of the usersGrid control
int Count = usersGrid.Rows.Count-((usersGrid.PageCount-1) * usersGrid.PageSize);

Second result of select query in Mysql c#

I can`t to return value from second query.
Part of code...
MySqlConnectionStringBuilder mysqlSB = new MySqlConnectionStringBuilder();
mysqlSB.Server = "localhost";
mysqlSB.Database = "test";
mysqlSB.UserID = "admin";
mysqlSB.Password = "1111";
MySqlConnection con = new MySqlConnection();
con.ConnectionString = mysqlSB.ConnectionString;
MySqlCommand Select = new MySqlCommand("select name from table_1 where id='1' ", con);
MySqlDataReader myReader;
con.Open();
myReader = Select.ExecuteReader();
while (myReader.Read())
{
count++;
}
string name = myReader["name"].ToString();
if (count == 1)
{
MySqlCommand Select2 = new MySqlCommand("select country from table_2 where name='"+name+"'", con);
MySqlDataReader myReader2;
myReader2 = Select2.ExecuteReader();
while (myReader2.Read())
{
count++;
}
return myReader2["id"].ToString();
}
If I delete second part, after if(count==1) and return name = all ok, but when I return id will error. Plase Tell why, because I need to return second, third... values of query.
Thank you!
If I were you I'd fill a datatable with the results of your query
See here
Connecting to a Mysql DB with C# - Need some with Datasets
I don't know what you want to do with the countries you select out but if its in a datatable you can then bind it to a dropdown or something
In your second you are returning id field and are only selecting the country field from the database. It isn't returning an id field for you to read from thus an error.

Implement search / lookup in Win Form

I have a 4 text boxes on a win form. [First Name, Last Name, Job, Description.]
I have one table.
I have the dataset and a data table configured and I can navigate the records.
I want to know how can I search based on first name, obtain the data from dataset/table and display the info based on what is in the text box.
how do I do this such as, obtain the row, "inc" where the
txtFirstName = ds.Tables[0].Column[1]
Then I can:
DataRow row = ds.Tables[0].Rows[inc];
txtFirstName.Text = row[1];
txtSurname.Text = row[2];
txtJobTitle.Text = row[3];
txtDepartment.Text = row[4];
sorry, found the solution.
First I created a search method which returned the row...
private int first_name_search(string fname)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if ((string)ds.Tables[0].Rows[i]["first_name"] == fname)
{
send = i;
//result stuff
break;
}
}
// return result;
return send;
}
I used this method in the Search button click method and displayed the data...
In a function that return a string[]:
string[number_of_infos] infos = null;
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
infos[0] = rdr["Surname"].ToString();
infos[1] = rdr["JobTitle"].ToString();
infos[2] = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Direct in your form:
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
txtSurname.Text = rdr["Surname"].ToString();
txtJobTitle.Text = rdr["JobTitle"].ToString();
txtDepartment.Text = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Else if you want to get the row infos:
foreach(DataGridViewRow row in your_DGV.Rows)
if(row["FirstName"].Value.ToString() == txtFirstName.Text)
{
txtSurname.Text = row["Surname"].Value.ToString();
txtJobTitle.Text = row["JobTitle"].Value.ToString();
txtDepartment.Text = row["Department"].Value.ToString();
break;
}
FYI, you can use LINQ extensions to do this:
var tbl = ds.Tables[0].AsEnumerable();
return tbl.Where(p => p["first_name"] == fname).FirstOrDefault();
Edit: To select all matching rows from the DataTable:
var results = from row in tbl.AsEnumerable()
where row["first_name"] == fname
select row;

Categories

Resources