问题
I am developing this website in ASP.NET and using C#. I am Getting the error that :Use of unassigned variable usn. The database is also not empty. My code is:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
SqlDataReader dr;
cn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Vijaylaxmi\Desktop\TrainReserveold\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
cn.Open();
cm.Connection = cn;
String usn;
cm.CommandText = "Select UserName from User where UserName='" + TextBox1.Text + "'";
dr = cm.ExecuteReader();
while (dr.Read())
{
usn = dr.GetString(0);
}
if (String.Compare(usn, TextBox1.Text) != 0)
{
Response.Write("Invalid user name... try again");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox1.Focus();
}
Response.Write("user valid now");
}
回答1:
Several problems I see here. In specific response to your question, you want to replace this:
dr = cm.ExecuteReader();
while(dr.Read())
{
usn = dr.GetString(0);
}
with this:
usn = cm.ExecuteScalar().ToString();
Be sure to check for DBNull first, just in case.
More generally, you want to
a) Parameterize your SQL (or, better, use a stored proc) instead of using raw input. This will protect you from SQL Injection attacks.
b) Not include your connection string directly in code. Put it in a config file. Most certainly don't post it on the internet.
回答2:
assing the usn string up top as
string usn = string.empty; then go from there
//create a Stored Procedure and put your Select Statement in there.. to avoid Sql Injection
cmd.CommandText = "name of your stored proc";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
I would also read my sql connectiong string from a web.config or app.config depending on the type of application you are running.
回答3:
change your cm.CommandText = "Select UserName from User where UserName= to
cm.CommandText = string.Format("Select UserName from User where UserName= '{0}'",Textbox1.Text);
来源:https://stackoverflow.com/questions/8593549/use-of-unassigned-variable-error