Second result of select query in Mysql c# - 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.

Related

Why my combobox only shows one item? c# mysql

enter image description hereI'm trying to show all my items on a combobox, but when y run my app I only get one item. Can you help me please, here's my code
try
{
MySqlConnection conection = new MySqlConnection("server = 127.0.0.1; database = sistemalaboratorio; Uid = root; pwd =;");
string selectQuery = "SELECT clavemateria FROM materia";
conection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, conection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read());
{
comboBox1.Items.Add(reader["clavemateria"].ToString());
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Assuming this read is happening before the page loads the combobox, make sure your materia table has more than 1 record in it.
These queries might usful to count the records in your SQL table in case you dont have direct access using SQL Management studio
SELECT COUNT(*) FROM materia WITH (NOLOCK)
-- NOLOCK here is for testing for this answer: no more, no less
or
SELECT clavemateria, count(*)
FROM materia
GROUP BY clavemateria
Also you can try this:
string qr1 = "select * from materia ";
SqlCommand cmd1 = new SqlCommand(qr1, con);
con.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
cmbcat.Items.Clear();
while (dr1.Read())
{
cmbcat.Items.Add(new Item(dr1["clavemateria"].ToString(), dr1["clavemateria"].ToString()));
}
con.Close();
Or refer to this example

SQL query data to cshtml

I'm not very good but I'm trying. I think there is something I don't understand somewhere...
I'm trying to get statistique from a DB like how many row got "X". Look simple. I know the SQL statement for it. There is a lot of walkthrough around. But I don't know how to make it appear on a page.
if(!Request.QueryString["RNum"].IsEmpty() ) {
searchTerm = Request.QueryString["RNum"];
selectCommand2 = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl = #0";
}
var Count = db.QueryValue(selectCommand2, searchTerm);
With a submit button to send the query how can I make it appear on a page?
just try this
searchTerm = Request.QueryString["RNum"];
string sqlSelect = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
// Set SqlDbType based on your DB column Data-Type
sqlCommand.Parameters.Add("#NoEmpl", System.Data.SqlDbType.Varcahr);
sqlCommand.Parameters["#NoEmpl"].Value = searchTerm ;
OR
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#NoEmpl", searchTerm ));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
//read here
}
}

Delete is not working in selected data at Datagrid view

I am trying to delete selected data from datagrid and database at the same time when user clicks on "Delete". It is not working and error message shows that "Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
Can anyone help me out this coding.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
string strSqlConnection = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB";
if ((dgvCustomerView.Rows.Count>0) && (dgvCustomerView.SelectedRows[1].Index != dgvCustomerView.Rows.Count))
{
SqlConnection sqlconn = new SqlConnection(strSqlConnection);
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
sqlconn.Open();
DataTable dtEmployee = new DataTable("Customers");
sdaCustomer.Fill(dsCustomers, "Customers");
sqlconn.Close();
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
MessageBox.Show("Deleted Successfully");
}
}
Instead of Remove you can rebind grid:
dgvEmpView.DataSource = dsCustomers;
dgvEmpView.DataBind();
MessageBox.Show("Deleted Successfully");
and for deletion ExecuteNonQuery is used:
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
sqlconn.Open();
cmd.ExecuteNonQuery();
Unless you have two rows selected referencing the SelectedRows[1] is wrong. The array indexes start always with zero. (Probably it is just a type because the other lines references correctly the row to be deleted)
if ((dgvCustomerView.Rows.Count>0) &&
(dgvCustomerView.SelectedRows[0].Index != dgvCustomerView.Rows.Count))
{
....
but then, to delete the row in the database, you don't need to use an SqlDataAdapter.
You could work directly with a SqlCommand
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
cmd.Parameters.AddWithValue("#iCustomerID", iCustomerID);
sqlconn.Open();
cmd.ExecuteNonQuery();
finally you could simply remove the selected row from the grid without further query
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
If do not use sql parameters then use plain sql query.
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = "+ iCustomerID.ToString();
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);

Checking and creating a View within MySQL via C#

I need to be able to see if a View already exists within my MySQL database and if it doesn't create one - through c#. I really could do with a bit of help and a point in the right direction - if possible.
You can use information_schema to query if a sever object, view in your case, exists. My example code snippet in C# is as below.
String conn = #"Data Source=myserverName;
Initial Catalog=myCatalogName;Integrated Security=True";
string cmdStr = "select count(*) from
information_schema.views where table_schema = 'mySchemaName'
AND table_name = 'MyViewName'";
using (MySqlConnection conn = new MySqlConnection(conn))
{
MySqlCommand cmd = new MySqlCommand(cmdStr, conn);
conn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int count = reader.GetInt32(0);
if (count == 0)
{
MessageBox.Show("View does not exists!");
MySqlCommand command = new MySqlCommand("Create View myView
as select
* from myTable;", conn)
command.ExecuteNonQuery();
}
else if (count == 1)
{
MessageBox.Show("View exists!");
}
conn.Close();
}
}
Can't you use create or replace view view_name as... ?

How to read specific column and cell in mysql in 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 ++;
}

Categories

Resources