i have connected my database with my windows form, i put the values of my database table column at a listbox, and i want to do the following: when i select an item from the listbox, another column of the table will appear in another textbox. To be more specific, drink names appear at the listbox( espresso,water etc) and i want their price to appear at a textbox , when they are selected from the listbox. I used the following code to do that:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=root;";
string Query = "select * from apps.drinks where drink_name is ='" + listBox1.Text + "'; ";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string dprice = myReader.GetString("drink_price");
pricebox.Text = dprice;
}
}
After i debug my project, it successfully shows the items at the listbox, but when i select them i get this error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '='Espresso'' at line 1"
The code from database is the following:
DROP TABLE IF EXISTS `apps`.`drinks`;
CREATE TABLE `apps`.`drinks` (
`drink_name` varchar(45) NOT NULL,
`drink_price` varchar(45) NOT NULL,
PRIMARY KEY (`drink_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into apps.drinks (drink_name,drink_price)
values ('Nes','1'),('Espresso','1'), (...)
Please can you help me??
The query where it fails on is:
"select * from apps.drinks where drink_name is ='" + listBox1.Text + "'; "
there you have is = which is incorrect, remove is so the query looks like:
"select * from apps.drinks where drink_name ='" + listBox1.Text + "'; "
Also take the comment of w0lf seriously and use prepared statements to prevent SQL injection.
Related
I try to write a program for updating data with id. When I write number for id (for example id=7), the program is run and works correctly. But when I write label text and convert to number, the code doesn't update and throws an error.
Here is my code:
private void yadda_saxla_update_Click(object sender, EventArgs e)
{
connect.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
// when i write "id=7" or other number data is update,
// but i want update with label text ( Convert.ToInt32( id_label.Text) )
// and gives error
cmd.Connection = connect;
cmd.ExecuteNonQuery();
connect.Close();
disp_data();
}
And the error is the following:
What can I do? Thanks...
As Others pointed it out in the comments you should not concatenate user inputs because it gives an attacking vector for SQL Injection. (or at least check for harmful inputs)
Otherwise the solution, I think, is that you should remove the ' because at the moment the command currently parsed as a varchar.
This part where id='"+Convert.ToInt32( id_label.Text)+"'" becomes where id='7' instead of where id=7
So unless your ID is stored as a varchar, this line should be changed
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
to
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id="+Convert.ToInt32( id_label.Text);
This is my first time creating a web api from scratch and I'm trying to get a selected value in a drop down bow to trigger an sql search and make the appropriate item appear in a text box. below is the relevant code
protected void btnRetrieve_Click(object sender, EventArgs e)
{
try
{
string pNameTemp = DropDownList1.SelectedValue;
myConnection.Open();
string query = ("SELECT sName from [dbo].[Table] WHERE (pName LIKE " + pNameTemp + ")");
SqlCommand sqlCmd = new SqlCommand(query, myConnection);
txtSkill.Text = sqlCmd.ExecuteScalar().ToString();
myConnection.Close();
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
it seems to search the correct name but when it comes to updating the txtSkill, I get the exception 'invalid column name' pop up, are there any obvious reasons as to why this is happening that i'm missing? any advice would be appreciated
In fact, you are missing '' for the parameter of the query.
Try to use this query.
SqlCommand sqlCmd = new SqlCommand(#"SELECT sName from [dbo].[Table] WHERE pName LIKE '{pNameTemp}'", myConnection);
But I recommend you to use SqlParameter in C# to avoid SQL Injection
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
myConnection.Parameters.AddWithValue("#field", pNameTemp);
But normally, when we use LIKE, we should put in % because it gives all results contains keyword. LIKE without % doesn't make sense. So :
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
command.Parameters.AddWithValue("#field", "'%" + pNameTemp + "%'");
There are some options in the LIKE clause:
%: The percent sign represents zero, one, or multiple characters
_ The underscore represents a single character
Using a 'label' I can display the date and time on the form, but I can't insert it into SQL Server. I don't know how to call it in the String InsertQuery= ?.
Here is the 'label' code which is displayed in the form:
label5.Text = DateTimeOffset.Now.DateTime.ToLongDateString(); // Date
label10.Text = DateTimeOffset.Now.DateTime.ToLongTimeString(); // Time
Here is the 'save' button code which is inside the save.
conn.Close();
conn.Open();
String InsertQuery = "INSERT INTO Stocks_Item VALUES('" + combo_main_type.Text + "','" + txt_stock_code.Text +"')";
SqlDataAdapter execute = new SqlDataAdapter(InsertQuery, conn);
execute.SelectCommand.ExecuteNonQuery();
MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
I also created two columns in a SQL Server table Stocks_Item:
Main_Item_Type | Stock_code| Date | Time
Don't concatenate together your SQL queries! This opens the door to SQL injection attacks.
Use parametrized queries instead!
Also: do not use names like Date or Time for your column names - those are reserved T-SQL keywords - try to use something more expressive, something that belongs to your problem domain - not just these overly generic column names.
Something like this:
string insertQuery = "INSERT INTO dbo.Stocks_Item (StockDate, StockTime) VALUES(#StockDate, #StockTime);";
SqlCommand cmdInsert = new SqlCommand(insertQuery, conn);
// define and set parameters
cmdInsert.Parameters.Add("#StockDate", SqlDbType.Date).Value = DateTime.Now;
cmdInsert.Parameters.Add("#StockTime", SqlDbType.Time).Value = DateTime.Now.TimeOfDay;
conn.Open();
cmdInsert.ExecuteNonQuery();
conn.Close();
MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Your Code Shows you are working with Web Forms,so alter your query like below and it will work.
String InsertQuery = "INSERT INTO Stocks_Item VALUES('" + combo_main_type.Text + "','" + txt_stock_code.Text +"','" + label5.Text.ToLongDateString() +"','" + label10.Text.ToLongTimeString() +"')";
I am trying to pull data from my table based on the button a user clicks, so if they click the 1940's button it will pull all products from that decade but I cant get the query to work. It has to do with the #decade parameter because that is where I am getting the user input from but it doesnt like it when I am trying to choose a column using that parameter
ImageButton decadeBtn = (ImageButton)sender;
var decade = decadeBtn.CommandArgument;
yearHead.InnerText = decade.ToString();
string cmd="";
DataSet ds;
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is null";
}
using (OleDbConnection dbConn = new OleDbConnection(connectionString))
using (OleDbDataAdapter dbCmdDecade = new OleDbDataAdapter(cmd, dbConn))
{
dbConn.Open();
dbCmdDecade.SelectCommand.Parameters.Add("#decade", OleDbType.Integer).Value = decade;
dbCmdDecade.SelectCommand.Parameters.Add("#line", OleDbType.VarChar).Value = productLine;
ds = new DataSet();
dbCmdDecade.Fill(ds, "products");
}
No you can't use a parameter in that way. As a rule, you cannot use a parameter to define a column name or a table name (or concatenating it to form a column name). A parameter could only be used to define a value used in the query. (or with a stored procedure to create an SQL Text inside the sp to be executed but that is another more complex story),
However, assuming that you are not allowing your users to type directly the decade value (Sql Injection vulnerability), then it is pretty simple to create a string with the column name desidered and use it in your query.
Add a method that just concatenate together you decade string with your prefix for the DECADE column
private string GetDecadeColumn(string decade)
{
return "DECADE_" + decade;
}
and in you query
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is null";
}
So ARCHIVE_DECADE_TBL has columns that are named something like DECADE_1990 with a value of 1990, DECADE_2000 with a value of 2000, etc?
It really should be designed to just be called "DECADE" with the value being 1990/2000/etc, but if that's not possible, you'll have to build your query dynamically. I don't believe those parameters will work to set the column name. They can set a value to check for, but not the column names.
You'll have to build the query out manually in c#, so something like:
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_" + decade + #" = #decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
Now, if I misunderstood and your column is actually named DECADE_#decade, then I think you'll just need to change your variable so it's not #decade, so something like #mydecade. The conflict there will confuse it.
Sooooo like...
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#mydecade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
And then down below:
dbCmdDecade.SelectCommand.Parameters.Add("#mydecade", OleDbType.Integer).Value = decade;
That probably shouldn't have an # in the column name though. :)
Can anyone tell whats wrong with my code? I have tried a million different things and I cant seem to make it work. I need to make a select in my mysql database and use the id from the table with the specified name I take from a combobox.
I took that name from the combobox and put it into a variable named "nomeres", now I need to do a select with it and take the id from that name from the database. Everything I try to do results in a mysql syntax error in line 1, but I've tried alot of things and its always the same. The database is fine, I tried the select directly from it myself, no tables or columns names are incorrect. This is the code im using:
MySql.Data.MySqlClient.MySqlConnection dbConn = new MySql.Data.MySqlClient.MySqlConnection("Persist Security Info=False;server=localhost;database=notas;uid=root;password=" + dbpwd);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres;
try
{
dbConn.Open();
} catch (Exception erro) {
MessageBox.Show("Erro" + erro);
this.Close();
}
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
idnumber = reader.ToString();
}
as others have already pointed you towards right direction,
i would like to suggest you to use parameterised queries to avoid SQL injection attacks.
Your query is open to SQL injection attacks so please read here
Try This: using parameterised SQL queries
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValue("#nome",nomeres);
You need to terminate the string in the query:
"SELECT id from residentes WHERE nome ='" + nomeres + "'"
In general, when trying to debug this type of code, it helps to print out the query string after all substitutions have been made.
cmd.CommandText = "SELECT id from residentes WHERE nome ='" + nomeres + "';";
actually you misses the semicolon of the query that have to enter within the quotes. and the second semicolon is for the end of statement.
But I preffer wo write commands like
cmd.CommandText = "SELECT id from residentes WHERE nome = #nome";
cmd.Parameters.AddWithValues("#nome", variableName);
then execute the query and retrieve your results.
Missing single quote:
"SELECT id from residentes WHERE nome ='" + nomeres + "'";
^