Reputation: 134
I have this code:
string strConnect = "Server=DESKTOP-2Q73COU\\SQLEXPRESS;Database=LoginApp;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(strConnect);
conn.Open();
MessageBox.Show("Connected to SSMS.");
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = " + Globals.username;
SqlCommand cmd = new SqlCommand(loadMainInfo, conn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblStanding.Text = (dr["Standing"].ToString());
lblName.Text = (dr["First Name"].ToString()) + " " + (dr["Last Name"].ToString());
lblTotalHours.Text = (dr["Total_hours"].ToString());
lblType.Text = (dr["Degree_type"].ToString());
lblDegree.Text = (dr["Degree"].ToString());
lblCurrentHours.Text = (dr["Current_hours"].ToString());
}
Specifically this line:
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = " + Globals.username;
If I replace the end of that line with:
Username = testuser"
The code will work fine and all labels below will be populated with the corresponding info from the tables where Username = testuser. However, if the user logs in with their username and the code is using the original line, I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
Any help?
Upvotes: 0
Views: 81
Reputation: 227
use a SqlParameter to do it as :
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = @paramName"';
SqlParameter param1 = new SqlParameter () ;
param1.ParameterName="@paramName";
param1.SqlDbType= SqlDbType.Varchar;
param1.Value= Globals.username;
cmd.Parameters.Add(param1);
Upvotes: 1
Reputation: 306
It looks like Globals.username
may not have a value when you're referencing it for your query string, as the SQL error you're getting occurs when there is nothing following the =
in the query.
I'd suggest using the debugger to look at the value of loadMainInfo
just after its been set (or otherwise add the line MessageBox.Show(loadMainInfo);
below).
Does the query string include the username value you expect?
Upvotes: 0
Reputation:
You could use String.Format
string loadMainInfo = String.Format(“SELECT * FROM Main_Information WHERE Username = {0}" ,Globals.username);
Upvotes: 0
Reputation: 227
You have make a wrong query, add the quote as this
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = '" + Globals.username + "'";
Upvotes: 0