Reputation: 686
I'm trying to setup a simple C# form to search one of our SQL databases. I keep getting a 'SQLException was Unhandled' error when I try to debug. I know the SQL statement works, I can run it just fine on my server. I think it's a problem with the way that I am trying to input the data from the TextBox
. Can someone give me some guidance?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace USER_Lookup
{
public partial class Search : Form
{
DataSet ds = new DataSet();
SqlConnection cs = new SqlConnection("Data Source=PC01; Initial Catalog=DB01; Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
public Search()
{
InitializeComponent();
}
private void button_Search_Click(object sender, EventArgs e)
{
string badgeCode = textBox_badgeCode.Text.Trim();
da.SelectCommand = new SqlCommand
("SELECT db01.dbo.staff.lastname AS 'Last Name', db01.dbo.staff.firstname AS 'First Name', db01.dbo.staff.badgecode AS 'User ID', db01.dbo.staffrole.name AS 'Role' FROM db01.dbo.staff, db01.dbo.staffrole, db01.dbo.staff_staffrole WHERE db01.dbo.staff.badgecode =" + badgeCode + "AND db01.dbo.staff.id = db01.dbo.staff_staffrole.staff_id AND db01.dbo.staff_staffrole.staffrole_id = db01.dbo.staffrole.id", cs);
ds.Clear();
da.Fill(ds);
dg.DataSource = ds.Tables[0];
}
}
}
Upvotes: 0
Views: 1098
Reputation: 216293
No space here
... db01.dbo.staff.badgecode =" + badgeCode + "AND db01.dbo.staff.id ....
^^^^
Also here you use maclive.dbo.staff.lastname
but there is no FROM or JOIN for this database
(typo?)
And, if db01.dbo.staff.badgecode
is a varchar field then you need single quotes around your badgeCode variable. However, string concatenation to form a SQL command is the sure path to Sql Injection attacks.
Change your code to use parameters
da.SelectCommand = new SqlCommand
("SELECT maclive.dbo.staff.lastname AS 'Last Name', " +
"db01.dbo.staff.firstname AS 'First Name', db01.dbo.staff.badgecode AS 'User ID', "+
"db01.dbo.staffrole.name AS 'Role' " +
"FROM db01.dbo.staff, db01.dbo.staffrole, db01.dbo.staff_staffrole " +
"WHERE db01.dbo.staff.badgecode =@badge AND db01.dbo.staff.id = " +
"db01.dbo.staff_staffrole.staff_id AND db01.dbo.staff_staffrole.staffrole_id = " +
"db01.dbo.staffrole.id", cs);
da.SelectCommand.Parameters.AddWithValue("@badge", badgecode);
Upvotes: 1
Reputation: 25628
I believe you need single quotes around badgeCode. Also, you're missing a space before the next AND. Try this:
...staff.badgecode = '" + badgeCode + "' AND...
Please bear in mind that your code contains an SQL Injection Attack vulnerability. You should use parameters to supply the badgeCode.
Upvotes: 2