I have a windows form application in which I have a combobox and a text box.
I want to take the value from the text box and store it in a string(eg: txt). And take the value from the combobox and store it in another string(Eg: combo)
I want to run the below query
"select * from order where"+combo+"='"+txt+"'";
I get the the below 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'='Brian'' at line 1
The problem is that you have no space between where and the value from the combo. This should do the trick:
"select * from order where "+combo+"='"+txt+"'";
Apart from that, don't do this, it opens you up for SQL Injection. You should use a SQLParameter to pass the value.
You are missing a white space after WHERE but since I didn't saw any complete answer, I take my chance..
I have a windows form application in which i have a combo box and a
text box.
Let's call your controls Combobox1 and TextBox1
I want to take the value from the text box and store it in a string(eg
txt). and take the value from the combo box and store it in another
string(Eg combo)
Ok. Let's take their values like;
string combo = Combobox1.Text;
string txt = TextBox1.Text;
So far, so good. Let's call your column names Column1 and Column2 in your table. So your query should be like;
"select * from order where Column1='" + combo + "' AND Column2='" + txt + "'";
But please don't use this way.
You should always use parameterized queries in your commands. It prevents, forget to use some quotes, commas etc.. But more important this kind of string concatenations are open for SQL Injection attacks.
And order is a reserved keyword in MySQL. You should use it with quotes.
Also use using statement to dispose your MySqlConnection and MySqlCommand.
Here a complete example;
using (var conn = new MySqlConnection(ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "select * from `order` where Column1=#combo AND Column2=#txt";
cmd.Parameters.AddWithValue("#combo", combo); // set the combo parameter
cmd.Parameters.AddWithValue("#txt", txt); // set the txt parameter
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
//You can read values here..
}
}
}
Try this :
"select * from order where " + combo + " = '" + txt + "';";
Just added a space between where and combo. Does it work ?
You forgot to take a space between where and combo
"select * from order where "+combo+"='"+txt+"'";
that will do
Apart from the missing space between WHERE and the column name, it may be you need to include the column name in backticks as well:
"select * from order where `" + combo + "` = '" + txt + "';";
Apart from SQL Injection and spacing issue in your syntax, whenever you need to construct the query where you are also injecting field names in it, we need to take care of following.
your combo should not accept a reserved SQL keyword. brackets can solve it but partially.
what if the combo field is not varchar, instead its int, then you need considerations to remove single quotes in your query.
have a look at sp_executesql, you may like it.
Related
I'm having problems with some code I'm trying to write. I'm doing something for suppliers orders, so I have a table which is named "encomendas_fornecedores" with a autoincrement field before the key that is the code of sale which consists in a EF before the number(which is a text field).
Here is the code:
connection.Open();
OleDbCommand comando1 = new OleDbCommand();
OleDbCommand comando2 = new OleDbCommand();
OleDbCommand comando3 = new OleDbCommand();
comando1.Connection = connection;
comando2.Connection = connection;
comando3.Connection = connection;
comando1.CommandText = "INSERT INTO encomendas_fornecedores (cod_encomenda_forn, cod_metodo, cod_forn, total_pagar_forn) VALUES('FO', '" + txtcodmetodo.Text + "', '" + txtcodforn.Text + "', '" + lbltotalapagar.Text + "'); ";// insert into table the values with a FO to cod
comando1.ExecuteNonQuery();
comando2.CommandText = "Select MAX(num_encomenda) From encomendas_fornecedores;";// selecting maximum num encomenda so I can isolate it and add to a text before(btw I do this in php/sql no problems
int numero = Convert.ToInt32(comando2.ExecuteScalar());//max num_encomenda
string codencomendaforn= "EF"+Convert.ToString(numero);// sales code completed
comando3.CommandText = "UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = '"+ numero +"';";//query that is giving me the problems, it says something like "type of data incorrect in data expression"
comando3.ExecuteScalar();//giving me error this line
connection.Close();
But now here's the catch the cod_encomenda_forn is text and the num_encomenda auto increment as it is in the sql, and I tried to show the query in a textbox to see if its anything is wrong but nothing seems wrong.
"UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = **'**"+ **numero** +"**'**;";//query that is giving me the problems,it says something like "type of data incorrect in data expression"
You are passing a string numero to a where statement that seems like it is expecting a number. As long as it is numeric it should work, but definitely not gauranteed to work. Second you are passing anothercodencomendaforn string to encomenda what is encomenda 's data type?
It appears that you are not handling potential datatype differences between your c# code and your SQL query. In addition single quoting '' around a value in a SQL statement tells the database engines that it is a string even if that is '1234'. While SQL will automatically convert some values it doesn't always. In addition c# .net library also looks for some conversion etc. before sending the SQL statement. To fix appropriately use parameters that are data typed to the database type in the SQL table. To fix it simply in the statement figure out your data types and fix the '' single quotes appropriately.
PS the people trying to help you in the comments were being nice and telling you the professional way of keeping your job in the future when you graduate after fixing this issue.
Ok been starring at this for a good while and i can not under stand why it is not updating my database..... I do not get an error messages it runs just fine. Code below
if (e.KeyCode == Keys.Enter)
{
// #WORK
string searchtext = txtAssetScanned.Text;
string searchcmd = "UPDATE " + lstCompCode.SelectedItem.ToString() + " SET " + lstCompCode.SelectedItem.ToString() + ".[Inventory Status]= \"FOUND\" WHERE [Inventory number] like '*" + searchtext + "';";
MessageBox.Show(searchcmd);
myConnection.Open();
OleDbCommand search = new OleDbCommand();
search.Connection = myConnection;
search.CommandText = searchcmd;
search.ExecuteNonQuery();
myConnection.Close();
}
There are a few things that pop out here :
Use Parameterized Queries. You should be using parameterized queries, concatenating in the manner you currently are can cause syntax issues and leave you vulnerable to SQL Injection.
Consider Using Single Quotes for Values. When setting string values in SQL, you should use single quotes 'value' as opposed to double quotes (i.e. "value").
SelectedValue over SelectedItem. Consider using the SelectedValue property as opposed to SelectedItem.ToString() to ensure you use the proper value.
Table Names as Parameters May Not Be Allowed. If you are using a table name as a parameter, which in many cases may be flat out rejected (as they are generally reserved for values), so fair warning.
Double-check for Typos. Finally, ensure the properties that you are targeting are correct and do not contain any typos (i.e. Foo.[Inventory number], etc.)
You can apply these changes as follows :
using(var connection = new OleDbConnection("{your-connection-string}"))
{
// Build your query with parameters
var query = "UPDATE ? SET [Inventory Status] = 'FOUND' WHERE [Inventory number] LIKE ?";
using(var command = new OleDbCommand(query, connection))
{
connection.Open();
// Add your parameters
command.Parameters.AddWithValue("#table",lstCompCode.SelectedValue);
command.Parameters.AddWithValue("#search", "*" + txtAssetScanned.Text);
// Now that your queries are added, perform your update
command.ExecuteNonQuery();
}
}
The Likely Issue
As I mentioned, some databases will not allow you to pass in table names as parameters without resorting to stored procedures, dynamic SQL, etc. You may be better off simply defining the table that you want to use directly :
var query = "UPDATE [YourTableName] SET [Inventory Status] = 'FOUND' WHERE [Inventory number] LIKE ?";
Since you cannot pass this through via parameters, you might consider adding some logic to determine which to use and hard-code it along with some sanitation to avoid possible nefarious behavior.
try
{
string Query = "SELECT Registrations list FROM [Records] WHERE textBox = '" + comboBox.SelectedValue + "'";
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
OleDbDataReader reader;
connection.Open();
reader = constr.ExecuteReader();
if (reader.Read())
{
OleDbParameter parameter = constr.Parameters.Add(new OleDbParameter("Registrations list", OleDbType.Integer));
textBox.Text = reader["Registrations list"].ToString();
}
me.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Im trying to get database values to display in textbox but keep getting the error, i've tried mostly everything possible
wrap the column name with square brackets
SELECT [Registrations list] FROM [Records] WHERE textBox
Otherwise sql server looks for a column called Registrations and then tries to alias it as [List]
Enclose the column name in square brackets.
SELECT [Registrations list]
If the column names contais space then you need to enclose the column name in square brackets else SQL Server will consider it as two column names and since comma will also be not present hence it will give you syntax error.
I suppose there is an error in the SQL
string Query = "SELECT Registrations list FROM [Records] WHERE textBox = '" + comboBox.SelectedValue + "'";
Between SELECT and FROM there should be a comma separated list of columns belinging to the table Records. If you want to label the column place the keyword as between the column name and uts label.
If you placed a white space in the column name (never saw, never did, don't even know if it's possible at all), try including the column name between single quotes. Or (much better) rename the column.
I tried to search a lot for tutorials on Npgsql and c#. but I couldn't resolve the below problem.
When I run the program, my programs stop and breaks at execute query. and when I try debug and check the return value from the execute reader is empty.
below is the sample code:
string user=textBox1.Text;
NpgsqlConnection dataconnect = new NpgsqlConnection(
"Server=127.0.0.1;Port=5432;User Id=dbuser;Password=dbpass;Database=dbname;");
string query = "Select USERNAME from helperdata.credentials where USERNAME = "
+ textBox1.Text + " and PASSWORD = " + textBox2.Text;
dataconnect.Open();
NpgsqlCommand command = new NpgsqlCommand(query, dataconnect);
NpgsqlDataReader reader = command.ExecuteReader();
if(reader.Read())
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login failed");
}
reader.Close();
dataconnect.Close();
When I try to run the below query in Pgsql it returns the data.
Select "USERNAME" from helperdata.credentials where "USERNAME" = 'admin'
I am new to Npgsql.
I would also like if someone could provide me some good tutorial sites which provides detail explanation of Npgsql and C#.
Thanks in advance.
I have identified two problems in your code. The first the usage of uppercase letters on PostgreSQL identifiers. PostgreSQL allows identifiers with other than simple lowercase letter, but only if you quote them.
In fact, you can use, for instance:
CREATE TABLE helperdata.credentials (... USERNAME varchar, ...);
But PostgreSQL will convert it to:
CREATE TABLE helperdata.credentials (... username varchar, ...);
So, to make it really left with uppercase, you have to quote it as following:
CREATE TABLE helperdata.credentials (... "USERNAME" varchar, ...);
And that seems to be the way you have created your table, and the problem with that is that always you refers to that table in a query, you'll have to quote it. So the beginning of your query should be:
string query = "Select \"USERNAME\" from helperdata.credentials ... ";
My recommendation, is to modify your column and table names to don't use such identifiers. For this case you can do:
ALTER TABLE helperdata.credentials RENAME COLUMN "USERNAME" TO username;
The second problem, is the lack of string quotation when you concatenated the username from the textbox into the query. So, you should do something as the following (BAD PRACTICE):
string query = "Select \"USERNAME\" from helperdata.credentials where \"USERNAME\" = '"
+ textBox1.Text + "' and \"PASSWORD\" = '" + textBox2.Text + "'";
There is a huge problem with that, you can have SQL injection. You could create a function (or use one from Npgsql, not sure if there is) to escape the string, or, more appropriately, you should use a function that accept parameters in the query using NpgsqlCommand, which you can simple send the parameters or a use a prepared statement.
Check the Npgsql documentation, and find for "Using parameters in a query" and "Using prepared statements" to see examples (there are no anchors in the HTML to link here, so you'll have to search).
I have the following code in asp.net:
using (OleDbCommand command = dbConnW.CreateCommand())
{
string CreateTableK = null;
CreateTableK += "Create Table DSKKAR00 (DSK_ID c(10),DSK_KIND N(1),MON_PYM C(3))";
OleDbCommand cmdCreateTable = new OleDbCommand(CreateTableK, dbConnW);
cmdCreateTable.ExecuteNonQuery();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(WorkRoomNo + ",");
sb.Append("1,");
sb.Append(",");
OleDbCommand cmd3 = new OleDbCommand("Insert into DSKKAR00 (DSK_ID,DSK_KIND,MON_PYM) Values (" + sb.ToString() + ")", dbConnW);
cmd3.ExecuteNonQuery();
But I have the following error:
Syntax error
In addition to what Chris has offered, you are starting your CREATE TABLE with a NULL string variable, then doing a += to it. From what I remember, a NULL += "anystring" will remain a null value... You might be crashing right there too.
Although VFP is not really suceptible to SQL Injection like other SQL engines, its good habit to do parameterizing. When you do, use "?" as a place-holder for the value you want to insert, and add parameters in the same order sequence as the "?" represent.
string CreateTableK =
"Create Table DSKKAR00 (DSK_ID c(10),DSK_KIND N(1),MON_PYM C(3))";
OleDbCommand cmdCreateTable = new OleDbCommand(CreateTableK, dbConnW);
cmdCreateTable.ExecuteNonQuery();
string MyInsert =
"insert into DSKKAR00 ( dsk_id, dsk_kind, mon_pym ) values ( ?, ?, ? )";
OleDbCommand cmd3 = new OleDbCommand( MyInsert, dbConnW);
cmd3.Parameters.AddWithValue( "parmSlot1", WorkRoomNo );
cmd3.Parameters.AddWithValue( "parmSlot2", 1);
cmd3.Parameters.AddWithValue( "parmSlot3", 'tst' ); // or whatever variable to put
cmd3.ExecuteNonQuery();
First off, any time you have an error it's usually best to post the entire error message you get.
Also, when trying to debug a query problem, you should emit the actual query being sent to your server/database and inspect it. This way you can find various problems like too many commas.
Speaking of which, looking at your code, you are concatenating a String and it really looks like you have way too many commas.
The emitted query looks like it will be:
insert into DSKKAR00(DSK_ID, DSK_KIND, MON_PYM) VALUES( X,1, ,)
where X is the value of your WorkRoomNo variable.
Obviously, that isn't valid syntax and would result in the error you've seen. The commas indicate there are 4 values being passed, but the insert query only identifies 3 columns.
The next issue has to do with the column definitions themselves. The first column of that table is a c(10); the third is a c(3). I'm a little rusty, but aren't those character fields?
If so then you need to adjust your string builder to add the appropriate quotes around the values...
Which leads us to the final problem: Don't use String concatentation to build queries. Use Parameterized queries