Having problems selecting data from my database, any clue as to what is wrong as I've been staring at this for for a solid 2 hours.... (have made a login system to which can write and use data but can't search for it)
4 Answers
Few things to consider here:
- DO NOT paste screenshots, copy/paste your code. It will be easier to read, easier to copy and to index for other SO users.
- DO NOT concatenate strings as SQL commands, use parameters
You have syntax error, your WHERE shoud be like WHERE Item = '" + textbox.Text + "'";
Correct way to query database is to make parameterized query, like this:
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.Connection = search;
cmd.CommandText = "SELECT * FROM [Table] WHERE Item = @item";
cmd.Parameters.Add("@item", SqlDbType.NVarChar).Value = txtLogin.Text;
sda.SelectCommand = cmd;
[Table]
and Item
should be real table name and column names from table you're trying to select data from.
I'm guessing that in your case select should be something like SELECT * FROM [Users] where Username = ...
-
@Igor, thanks. I notices lack of single quotes but forgot
Table
issue. :)– NinoJun 7, 2017 at 12:39
The problem is with SQL Query you are trying to execute.
Make sure if you are passing correct table name:
SELECT * FROM TABLE WHERE ...
Table is a keyword in SQL Server so it cannot be use like this in query.
Event if you have a table in db with name 'Table' then use following query
SELECT * FROM [TABLE] WHERE ...
Table
is a keyword on SQL you cant use it as is. If indeed you have named one of your tables as table, which I highly recommended not to, you must use brackets:
Select * from [Table]
The problem is with SQL Query you are trying to execute.
SELECT * FROM TABLE WHERE "condition";
use that query.
Table
is a reserved word and so needs escaping, ifname of item
is a column name it likewise needs escaping due to the spaces:select * from [TABLE] where [name of item] = 'xxx'
- You also must use a parameterize statement as currently you have an SQL Injection vulnerability. You should also be usingusing () {}
constructs to ensure disposal.Table
. Also use parameters for your values, see Best Practices - Executing Sql Statements.