How to dynamically add lables for every name in MYSQL database? - c#

I have a MYSQL database and I am trying to get the first name and last name of every student I put in the database and dynamically show them as a label in my WPF form, here is what I got so far
string connstr = "Server=localhost; Database=login; UID=root; Pwd=password";
MySqlConnection connc = new MySqlConnection(connstr);
MySqlCommand command;
connc.Open();
// Label[] labels = new Label[n];
try
{
command = connc.CreateCommand();
command.CommandText = "SELECT First_name, Last_name FROM Students";
command.ExecuteReader();
MessageBox.Show("S");
}
catch (Exception ex)
{
MessageBox.Show("something went wrong: " + ex.ToString());
}
finally
{
connc.Close();
}
So how could I add all my entry's in the database to a label?

ExecuteNonQuery method just executes your query. You can't get your values with it.
You need to use ExecuteReader at least to get your values. You can read your column values in a while statement with MySqlDataReader.Read() method. This method reads your query row by row.
Also use using statement to dispose your MySqlConnection, MySqlCommand and MySqlDataReader.
using(MySqlConnection connc = new MySqlConnection(connstr))
using(MySqlCommand command = new MySqlCommand("SELECT First_name, Last_name FROM Students", connc))
{
using(MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// reader[0] gets you first column which is First_name
// reader[1] gets you second column which is Last_name
// Do your label assingments..
}
}
}

First , ExecuteNonQuery() method is used for DML statements INSERT ,UPDATE , DELETE .
Use ExecuteReader() method.
command = connc.CreateCommand();
command.CommandText = "SELECT First_name, Last_name FROM Students";
SqlDataReader dr = command.ExecuteReader();
string result=string.Empty;
while(dr.Read())
{
result += dr["First_name"].ToString() + " " + dr["Last_name"].ToString();
}
lableId.Content=result;

Related

C# : querying multiple columns into textboxes

This is my code, and I want to be able to search for a name, and then pull from the database the name, status, member_id into the textboxes in my form.
I got the name to work but how do I get the other columns and parse the output into the textboxes with the additional columns (member_id, status)? Let's say the other textboxes have the standard name such as textbox2, 3, 4...
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
string sql1 = null;
SqlDataReader dataReader;
connetionString = "Data Source=......"
sql = "SELECT NAME FROM Test_Employee WHERE Name LIKE '" + textBox1.Text.ToString() + "%'";
connection = new SqlConnection(connetionString);
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
textBox9.Text = dataReader[0].ToString();
textBox7.Text = dataReader[0].ToString();
}
connection.Close();
}
Are the fields Member_Id and Status also in the table Test_Employee? You can add them in your Select statement and get them from your SqlReader, like the code below (assuming you are using c#7 and below). You may copy and paste this code.
var connectionString = "";
var sql = #"SELECT TOP 1 Name, Member_Id, Status
FROM Test_Employee
WHERE Name LIKE #name + '%'";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("name", SqlDbType.NVarChar, 100).Value = textBox1.Text.ToString();
connection.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
textBox9.Text = dataReader["Name"].ToString();
textBox7.Text = dataReader["Name"].ToString();
textBox2.Text = dataReader["Member_Id"].ToString();
textBox3.Text = dataReader["Status"].ToString();
}
}
You will notice that instead of including the Textbox1.Text's value in your Select statement, it is added as a parameter in the SQLCommand object's Parameters. In this way your query is protected from SQL Injection. If you want to learn more, you can search c# sqlcommand parameters and why it is very important to build data access code this way.
Also, notice that I added Top 1 in your Select statement, and instead of using while, I am using if. This is because a textbox can only hold 1 result at a time in a comprehensible way. If you meant to show multiple results clearly, you need to use a different control other than a TextBox.
The using statements allow you to dispose the connection, so you don't have to call connection.Close().

Runaround with trying to read mdf

I am having trubble to get the stored values from my mdf. I can see they are there and all is working as suposed to untill i a want to get hold of them, I just cant. I have been trying for almost 48h and I just cant get it to work. I read tons of guides and other threads here but nothing seems to work for me. I guess I just have get my head around this way of accessing and mdf SQL database. I just want it to give up the secrets stored on specified row.
I am trying to access the three values stored on a numbered row(specified as int row) in a mdf file called Table1 and return them to the caller.
My code I have been fighting the last hours is this:
public static void loadAnimalData(int row, out string stringId, out string name, out double age)
{
int antal = AnimalsDBCount();
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|path.to.db|DBList.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(connString);
con.Open();
using (SqlCommand command = new SqlCommand("SELECT ID WHERE ID = " + row, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
m_stringId = reader.GetString(0);
m_name = reader.GetString(1);
m_age = reader.GetDouble(2);
}
}
con.Close();
stringId = m_stringId;
name = m_name;
age = m_age;
}
I am lost here, I can't seem to get access to specied row or values, Where am I going wrong?
Might you want is;
m_stringId = reader[0].ToString();
m_name = reader[1].ToString();
m_age = reader[2].ToString();
SqlDataReader read rows, since you select one, you can't access others.
Provides a way of reading a forward-only stream of rows from a SQL
Server database.
You shoudl select other columns also like;
using (SqlCommand command = new SqlCommand("SELECT ID, NAME, AGE WHERE ID = " + row, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
m_stringId = reader.GetInt32(0);
m_name = reader.GetString(1);
m_age = reader.GetString(2);
}
}
You are only selecting the ID (which is already known), not any other columns.
Try changing:
"SELECT ID WHERE ID = " + row
to
"SELECT ID, NAME, AGE WHERE ID = " + row
You may wish to select your columns in your select statement
using (SqlCommand command = new SqlCommand("SELECT ID, name, age from TableOfInterest WHERE ID = " + row, con))
Then you can use them in your Reader

Return value of a select statement

I want to retrieve the resulting value of a select statement into a string variable. Like this:
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
I want to place the selected treatment value into a string variable. How can I do this?
Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.
try
{
SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{
}
while(dr.Read())
{
string treatment = dr[0].ToString();
}
Or better, use a using statement for it.
using(SqlDataReader dr = cmd1.ExecuteReader())
{
while(dr.Read())
{
string treatment = dr[0].ToString();
}
}
But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-
cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());
Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.
Execute Scalar: Getting Single Value from the Database method to retrieve a single value (for example, an aggregate value) from a database.
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
var treatment = cmd.ExecuteScalar();
}
Other Way: ExecuteReader()
try
{
cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
cmd1.Parameters.AddWithValue("#patientID", this.DropDownList1.SelectedValue);
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
int PatientID = int.Parse(dr["treatment"]);
}
reader.Close();
((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
Response.Write(exc.ToString());
}
the answer:
String res = cmd1.ExecuteScalar();
the remark: use parametrized query to prevent sql injection
There is a lot wrong with your example code.
You have inline sql, which opens you up to sql injection in a major way.
You are using ExecuteNonQuery() which means you get no data back.
string sSQL = "SELECT treatment FROM appointment WHERE patientid = #patientId";
OleDbCommand cmd1 = new OleDbCommand(sSQL, GetConnection()); // This may be slight different based on what `GetConnectionReturns`, just put the connection string in the second parameter.
cmd1.Parameters.AddWithValue("#patientId", text);
SqlDataReader reader = cmd1.ExecuteReader();
string returnValue;
while(reader.Read())
{
returnValue = reader[0].ToString();
}
You just need to use the ExecuteScalar method of the command - this will give you the value at the first row and column of the result set.
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
var result = cmd1.ExecuteScalar();
If your SQL statement returns more than one row/column then you can use ExecuteReader().
You need to use OleDbAdapter.
string connection = "your connection";
string query = "SELECT treatment FROM appointment WHERE patientid = " + text;
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.Fill(dataset);
SqlConnection dbConnect = new SqlConnection("your SQL connection string");
string name = " 'ProjectName' ";
string strPrj = "Select e.type, (e.surname +' '+ e.name) as fulln from dbo.tblEmployees e where id_prj = " + name;
SqlCommand sqlcmd = new SqlCommand(strPrj, dbConnect);
SqlDataAdapter sda = new SqlDataAdapter(strPrj, dbConnect);
ds = new DataSet();
sda.Fill(ds);
dbConnect.Open();
sqlcmd.ExecuteNonQuery();
dbConnect.Close();

trouble updating to mysql inside reader loop

I am looping through these mysql rows and processing data. But, in part of the processing I am also wanting to update into the same mysql table.
This is not working for me.
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
CODE
string connString = "Server=localhost;Port=3306;Database=communications;Uid=myuser;password=mypass;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(reader["account"].ToString());
SendFax(reader["filepath"].ToString(), reader["filepath"].ToString(), reader["id"].ToString(), reader["fax"].ToString());
string id = reader["id"].ToString();
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
}
}
I think that last command.ExecuteReader() tries to open one more reader, but it is not possible to do with one connection. Close first open reader firstly, then modify this table; or try to use command.ExecuteNonQuery() method.

how to fill textbox from dataset?

i run this and i want to fill textbox txtFname with data - but it dont do nothing
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();
txtFname.Text = dsView.Tables[0].Rows[3][0].ToString();
txtFname.DataBind();
Conn.Close();
}
how to do it ?
thank's in advance
using (Conn = new SqlConnection(Conect)) {
try {
// Attempt to open data connection
Conn.Open();
// Compose SQL query
string SQL = string.Format("SELECT * FROM MEN WHERE id = '{0}'", txtBAR.Text.Trim());
using(SqlCommand command = new SqlCommand(SQL,Conn)) {
// Execute query and retrieve buffered results, then close connection when reader
// is closed
using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) {
// Assign txtFname value to search value and clear value if no results returned
txtFname.Text = reader.Read() ? reader[0].ToString() : string.Empty;
reader.Close();
}
}
}
finally {
// Regardless of whether a SQL error occurred, ensure that the data connection closes
if (Conn.State != ConnectionState.Closed) {
Conn.Close();
}
}
}
However, I would advise that you
update your SQL query to return the
actual column names instead of *
replace reader[0].ToString() with
reader["FirstName"].ToString()
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
SqlCommand command= new SqlCommand(SQL,Conn);
SqlDataReader reader = command.ExecuteReader()
reader.Read();
//Call Read to move to next record returned by SQL
//OR call --While(reader.Read())
txtFname.Text = reader[0].ToString();
reader.Close();
Conn.Close();
}
Edit: I just noticed 'dataSet' not database, anyway you are reading third row, is your query returns more than one row?

Categories