Error when using textbox values inside string sql - mysql

"Select item from table1 where Spare parts='"+ textbox1.text+"'".
I have tried to replace item with Textbox2.text.
I used :
"Select'"& textbox2.text& "' from table1 where Spare parts='"+ textbox1.text+"'"
I got error.
I used "+ textbox2.text+" I got error too

What you have here is one of the fastest ways out there to get your app hacked. It is NOT how you include user input in an SQL statement.
To explain the right way, I also need to include the connection and command objects for context, so I may also have a different pattern for how I handle these than you're use to. I'm also assuming the mysql tag in the question is accurate (though I have my doubts), such that the correct code looks more like this:
string SQL = "Select item from table1 where `Spare parts`= #SpareParts";
using cn = new MySqlConnection("connection string here")
using cmd = new MySqlCommand(SQL, cn)
{
cmd.Parameters.AddWithValue("#SpareParts", TextBox1.Text);
cn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// ...
}
}
}
Note the backticks around Spare Parts, so it will be correctly treated as a single object name by MySql.

Related

Visual basic datagridview result showing numbers of results not the text

Might be a bad title but as a non-english speaking person not everything is simple.
My problem is the following:
Fetching data from Mysql database (No problem)
Adding a Combobox in my Datagridview (No problem)
Inserting the result into that combobox (Problem)
What happens is that the combobox shows me the number of results, it is showing me 212 as a single possibility to click and not the value of the MySQL cell.
My code looks like this:
'//Henter drivere fra Printer Installer Database //'
mysqlconnpi.Open()
query = "Select model_name from printer_installer.ppp_drivers"
data = New DataTable
dataAdap = New Devart.Data.MySql.MySqlDataAdapter(query, mysqlconnpi)
Dim cmb As New DataGridViewComboBoxColumn()
cmb.HeaderText = "Select Data"
cmb.Name = "cmb"
cmb.MaxDropDownItems = 100
cmb.Items.Add(dataAdap.Fill(data))
DataGridView1.Columns.Add(cmb)
The result is this:
What is wrong with my code?
Also, I found out that the combobox only could handle 100 items, is there a way for my to get more? I currently have 212 drivers in the database I want to list.
EDIT:
I testet to add this line:
DataGridView1.DataSource = data
to the code just to check if "data" even had items.
the result is this:
Not allowed to insert embedded, image is here.
The code is now:
'//Henter drivere fra Printer Installer Database //'
mysqlconnpi.Open()
query = "Select model_name from printer_installer.ppp_drivers"
data = New DataTable
dataAdap = New Devart.Data.MySql.MySqlDataAdapter(query, mysqlconnpi)
Dim cmb As New DataGridViewComboBoxColumn()
cmb.HeaderText = "driver"
cmb.Name = "cmb"
cmb.MaxDropDownItems = 100
cmb.Items.Add(dataAdap.Fill(data))
DataGridView1.Columns.Add(cmb)
DataGridView1.DataSource = data
'DataGridView1.DataSource = dataAdap.Fill(data)
'-------------------------------------------------'
The DataGridView might be looking at the string length which is the property of string the result of the query so you might want to send the result by wrapping your string. You can use linq in place of your sql query.
From model in printer_installer.ppp_drivers select new with {Key .name =model.model_name}

Get AES_DECRYPT Value From "MySQL" in ASP.NET webPage

My "MySQL Connection" is perfectly working in ASP.NET
I can get and insert value in database perfectly
The Problem Occurs when I want to get a Password value from the following Table
The Table has columns as,
ID->Integer
name->Varchar
mobile_no->VarChar
password->blob
Password column gives me problem
MySqlCommand cmd2=new MySqlCommand("SELECT AES_DECRYPT(password,'qwerty') FROM mytable1 where mobile_no=#z2", connection);
cmd2.Parameters.AddWithValue("#z2", TextBox1.Text);
String pass = cmd2.ExecuteScalar().ToString();
The 3rd line is giving me problem.
I want to compare this "pass" with ""Textbox2.text""
OR
I want to display that password on webpage (just fro try)
i.e., ""Label1.text=pass""
Its displaying this on Label...... ""System.Byte[] ""
try like this:
MySqlCommand cmd2=new MySqlCommand("SELECT AES_DECRYPT(password,'qwerty') FROM mytable1 where mobile_no=#z2", connection);
cmd2.Parameters.AddWithValue("#z2", TextBox1.Text);
//prepare adapter to run query
adapter = new MySqlDataAdapter(cmd2);
DataTable Dt = new DataTable();
//get query results in DataTable
adapter.Fill(Dt);
string pass = Dt.Rows[0][0].ToString();
// your password contains Byte array as You said it is showing System.Byte[]
//You should convert it /Decode it into proper Plain text
EDIT
Depending On Your Encoding You can try like this
string result = System.Text.Encoding.Default.GetString(pass);
string result = System.Text.Encoding.UTF8.GetString(pass);
//dispaly result on label

VB.NET: Populating ComboBox Using MySQL Query

I am trying to populate a Combobox from a MySQL database; but I don't get anything.
Below is the code.
Table: Class
Columns: Code, State
sqlstr = "SELECT * FROM Class WHERE State= Not Started"
DBCmd = New MySql.Data.MySqlClient.MySqlCommand(sqlstr, DBConn)
DBDR = DBCmd.ExecuteReader
While (DBDR.Read())
CB_Class.Items.Add(DBDR("Code"))
End While
DBCmd.Dispose()
DBDR.Close()
I believe the result is wrong, because there are at least 2 records with their state values set as "Not Started". What is wrong? Is there anything wrong with the way I've written "State= Not Started" ?
The command text doesn't seems correct. It lacks the single quote around the string to search
sqlstr = "SELECT * FROM Class WHERE State='Not Started'"
^ ^
If State is a string field then every search over it should be enclosed in single quotes.
Beware of the potential problems when the string to search contains a single quote.
In this simple case you could use directly the string constant, but if you render your search dynamic with user input then you should use parametrized queries.

ADODB Command failing Execute with parameterised SQL query

I have the following JScript code:
var conn = new ActiveXObject ("ADODB.Connection");
conn.Open("Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=blah_blah_blah;User=foo;Password=bar;");
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = conn;
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE :search ORDER BY id";
var search = "test";
try{
cmd.CommandText = strSQL;
var param = cmd.CreateParameter(':search', 200, 1, 100, search);
cmd.Parameters.Append(param);
var rs = cmd.Execute();
}
catch (ex) {
Application.Alert("Error retrieving id information from database.");
}
I've verified (by printing them) that the Connection object is set to be the Command's ActiveConnection, the parameter object has the correct value and the Command object has the correct SQL query as its CommandText. I also inserted an alert statement after each line in the try block to see where the error was occuring - it's fine after cmd.Parameters.Append but the exception gets thrown upon running the Execute statement.
I've tried displaying the actual exception but it's just a generic 'Object error' message.
The query executes fine and returns the correct result set when I just execute the SQL query (without the parameter) straight through the Connection object, but seems to fail when I use a parameterised query with the Command object.
As far as I can see all settings and properties of the Command and Connection objects are correct but for whatever reason it's throwing an exception.
Any help with this would be much appreciated.
With ODBC and ADO, generally speaking, a question mark ? is used as the placeholder for parameters. Parameters are bound in the order they are appended to the Parameters collection to the placeholders in the command. In your example, replace strSQL with:
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE ? ORDER BY id";
You can still name the parameter that you create, but the only purpose it would serve is to be able to reference it by name later (e.g., with cmd.Parameters.Item(":search")).

how to escape for mysql in asp.net?

What's the ASP.NET equivalent of this PHP code?
$db = new mysqli(/*some data*/);
$db->query('INSERT INTO `log` (`msg`) VALUES ("'.$db->real_escape_string($_POST['mesg']).'");');
Im only interested in mysqli_real_escape_string, but the only examples I can find on Google for ASP.NET and SQL are all injectable.
So my question is: How do I pass user data to SQL in ASP.NET using ADO.NET?
If you use replace of regex, please base your example on this code.
When using this approach, you'll want to look into using parameterized SQL in your code.
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet userDataset = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter("SELECT * FROM Log WHERE Message = #Message", connection);
myCommand.SelectCommand.Parameters.Add("#Message", SqlDbType.VarChar, 11);
myCommand.SelectCommand.Parameters["#Message"].Value = messageString;
myDataAdapter.Fill(userDataset);
}
First of all, you should use properties if possible. Then you don't need to escape the strings yourself.
If you can't do that, you need to escape both backslashes and apostrophes:
public static string EscapeForMySQL(string str) {
return str.Replace("\\", "\\\\").Replace("'", "\\'")
}
If possible please refactor to avoid dynamic sql or use parameterized queries.
Use Parameterized queries for ODBC (I believe in oledbcommand will work here as well)
http://weblogs.asp.net/cumpsd/archive/2004/04/05/107456.aspx
See my talk on it - its the first subject:
http://channel9.msdn.com/Events/TechEd/NorthAmerica/2011/DEV333