C# Mysql Select with Textbox Text - c#

Im trying to select a row in mysql database using a textbox's text.
However when I use the following code I get an error.
MySqlCommand command = connection.CreateCommand(); //we create a command
command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ; //in commandtext, we write the Query
MySqlDataReader reader = command.ExecuteReader(); //execute the SELECT command, which returns the data into the reader
while (reader.Read()) //while there is data to read
{
MessageBox.Show(reader["info"].ToString());
}
It works fine with letters but when I try to use a question mark or anything like that i get the following error:
"Parameter '?' must be defined."

instead of
command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ;
Use this
command.CommandText = "SELECT * FROM info where id=#id";
command.Parameters.AddWithValue("#id",textBox1.Text);

you better use parameters in this case
command.CommandText = "SELECT * FROM info where id=#id";
then you need to set the parameter value
command.Parameters.AddWithValue(#id, textBox1.Text);
full code:
string queryString="SELECT * FROM info where id=#id";
using (MySqlConnection connection = new MySqlConnection(connectionString))
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
connection.Open();
command.Parameters.AddWithValue("#id", textBox1.Text);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// do something ...
}
}
}
update :
change your parameter value setting line as below
command.Parameters.AddWithValue("#id", textBox1.Text);

Related

c# Mysql how properly use AND with Where clause

here's my code
int indextest = 0;
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select backup,Client,No_Projet,Description from historique Where id= #dataID and index= #indexID";
cmd.Parameters.AddWithValue("#dataID", soumissionId.Text);
cmd.Parameters.AddWithValue("#indexID", indextest);
cmd.Connection = connection;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Cant figure how format my string form having the and working.
I'm always getting error near index= 0
Can anyone help me please
My SQL uses ` characters to enclose names, you can use them in your query:
cmd.CommandText = "Select `backup`,`Client`,`No_Projet`,`Description` from `historique` Where `id` = #dataID and `index` = #indexID";

C# checking if order number already exists

I've been looking into How to check user id already exists to see how to do this.
I am trying to get this working in my code, however it's not working. I don't get errors or something, but it just write data in database even if order number already exists.
The function:
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
cmd.Parameters.Add(param);
//sqlCommand.Connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
reader.Close();
}
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}
Sorry for this kinda well known and duplicated question, but for some reason I can't get it working.
You called the wrong command, change
SqlDataReader reader = sqlCommand.ExecuteReader();
to
SqlDataReader reader = cmd.ExecuteReader();
The problem is here:
SqlDataReader reader = sqlCommand.ExecuteReader();
You should execute the other command first
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
The latter command, when will be executed will tell you if there is any record in the testtabel table. If there is, then you should show the message:
Order already exist
Otherwise, you will execute your first command, that will insert the rows.
By the way, please try to avoid string concatenation, when you write sql queries. It is one of the most well known security holes. You code is open to SQL injections. You could use parameterized queries:
String query = "INSERT INTO testtabel (knaam, korder) VALUES (#knaam, #korder)";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
sqlCommand.Parameters.Add(new SqlParamete("#knaam",knaamTextBox.Text));
sqlCommand.Parameters.Add(new SqlParamete("#korder",kordernrTextBox.Text));
While your code is full of problems (magic pushbutton, SQL injections, absence of usings), there is main one. The approach you want to implement will fail on concurrent inserts, and must not be used.
Imagine, that two users run this code against the same database, using the same korder value:
1st executes SELECT - record with the given value doesn't exist;
2nd executes SELECT - record with the given value doesn't exist;
1st executes INSERT - record with the given value does exist;
2nd executes INSERT - ooops... we have a duplicate;
To avoid duplicates you must use unique indexes in database. Do not rely on your code.
You check HasRows for INSERT INTO testtabel bla...bla..bla.. not for `elect * from testtabel where korder'
Maybe you can use this (it comes from my head and not compiled, please adjust it with your own case)
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
//sqlCommand.Connection.Open();
SqlDataReader cmdReader = sqlCommand.ExecuteReader();
if (cmdReader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
cmdReader.Close();
}
SqlDataReader reader = sqlCommand.ExecuteReader();
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}

Select * From table Where column Like statement c#

I failed to get the correct result with this code in Form2:
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * From udbTable Where Username Like '" + f1.textBox1.Text + "%'", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
label5.Text = reader["Username"].ToString();
}
conn.Close();
I have 3 samples data in the table, but i'm always getting the same result which is the first entry of the database. Whenever i input the last entry or second entry in the textbox1.Text, i still getting the first entry.
textbox1.Text is from Form1, and i set it's property Modification to Public.
label5.text is the output.
try this fix
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=conn;
command.CommandText = "Select * From udbTable Where Username Like ?";
cmd.Parameters.Add("#Username",OleDbType.VarChar);
cmd.Parameters["#Username"].Value=f1.textBox1.Text;
OleDbDataReader reader = cmd.ExecuteReader();

MySQL select query with parameter

I am trying to use MYSQL select query with c#.
Following query for searching "ID" is working fine:
conn = new MySqlConnection(cs);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "select * from catalog_product_entity where entity_id = ?Id";
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
cmd.Parameters.Add("?Id", SqlDbType.Text).Value = ProductList[i].ProductId.ToString();
adp.Fill(MagentoProduct);
Now, I want to search exact string value in table. I am using following code and its giving empty result:
My Code:
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand("select * from catalog_category_entity_varchar where value = #Value;", conn);
cmd.Parameters.AddWithValue("#Value", "Storybooks");
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
log.WriteEntry(r.GetString("value"));
}
This is the problem:
where value = '?cname'
That's specifying ?cname as the literal value you're searching for - when you actually just want the parameter. Remove the quotes and it should be fine:
where value = ?cname
(You should use using statements for the connection and command, mind you...)
You could try SQL Reader
c = new MySqlCommand("select * from catalog_product_entity where column_nam = #Value;", conn);
c.Parameters.AddWithValue("#Value", your string);
MySqlDataReader r = c.ExecuteReader();
and then use Reader methods like reader.GetString("column_name"), ....

SqlDataReader Execution error

i m trying to retrieve the Specialization ID from a table called Specializationtbl, using C# MSVS 2008 and the table includes SpecializationName and SpecializationID beside some other rows and my question is related to some error " No Data to present ", the command goes as bellow:
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
DBcnction.Open();
SqlDataReader ReadSpecID_ = READSpecID.ExecuteReader();
ReadSpecID_.Read();
int SpecID_ = Convert.ToInt16(ReadSpecID_["SpecID"].ToString());
DBcnction.Close();
i also tried to Select the "SpecID" instead of all the rows, but cant seem to seal the query correctly and keep receiving "No data present " error, any idea where am i making the mistake?
1) Try opening DBcnction before assigning the value to READSPecID
DBcnction.Open();
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
2) Run the command in SSMS:
SELECT * FROM Specializationtbl WHERE SpecializationName ='yourvalue'
and see if any results are returned
3) Check comboBox1.Text has a value in it
4) Validate the contents of comboBox1.Text (Or use paremetrised queries or a stored procedure) to ensure you do not become a victim of SQL Injection: http://en.wikipedia.org/wiki/SQL_injection
Refactor to solve your TWO problems:
Your SQL injection problem when building your SQL statement.
Use ExecuteScalar if you only need one value.
Implement using blocks.
string retVal;
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
retVal = cmd.ExecuteScalar().ToString();
}
int specID = int.Parse(retVal);
If you really needed more than one value from your statement:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID, Value2 FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
var dr = cmd.ExecuteReader();
while (dr.Read())
{
Customer c = new Customer {
ID = dr["SpecID"].ToString(),
Value = dr["Value2"].ToString(),
};
}
}
Need to first test if there are any rows. I suspect the query is returning zero rows.
if (ReadSpecID_.HasRows)
{
ReadSpecID_.Read();
}

Categories

Resources