2011-12-21 52 views
0

我正在ASP.NET中开发此网站并使用C#。我得到的错误是:使用未分配的变量usn。数据库也不是空的。 我的代码是:“使用未分配的变量”错误

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"); 
} 
+3

你应该在'using'语句中创建'SqlConnection','SqlCommand'和'SqlDataReader'。 – Oded

+2

现在你正在粗鲁。尽快地?你知道,我没有为此付出代价。这只是让我失去了回答所有的兴趣。 – Oded

+0

我也会考虑重写你创建连接和命令的方式我会发布一个例子,它会让你更容易地遵循你可能导致你自己的困惑 – MethodMan

回答

1

assing美国海军串起来顶部,

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; 

我也从一个web.config或app.config中根据应用的类型,阅读我的SQL字符串接法你正在跑步。

+1

分配NULL可能会更好,因为空的用户名可能无效,即使DB中没有其他用户存在。 –

+0

Empty只是一个初始化器,我会真正推荐他重构他的连接,使用类似这样的东西,然后在使用内部创建/分配他的命令对象(SqlConnection sqlConnSqlConnection = new SqlConnection(strConnectionString)){} – MethodMan

+0

所有的代码都很糟糕。但我想罗马不是一天建成的。没有理由引入更多的错误:) –

0

改变你的cm.CommandText =“选择用户名从用户其中username = 到我在这里看到

cm.CommandText = string.Format("Select UserName from User where UserName= '{0}'",Textbox1.Text); 
+1

这不会阻止SQL注入 –

+0

是的,他可以随时更改,以提供存储过程中的sql命令..我知道,但好点.. – MethodMan

+0

存储过程不会阻止注入。命令参数做。 –

3

几个问题在你的问题具体的回应,要更换此:

dr = cm.ExecuteReader(); 
while(dr.Read()) 
{ 
    usn = dr.GetString(0); 
} 

与此:

usn = cm.ExecuteScalar().ToString(); 

请务必检查DBNul首先,以防万一。

更一般地,要
一)参数化的SQL(或更好,使用存储过程),而不是使用原始输入。这将保护您免受SQL注入攻击。
b)不要在代码中直接包含连接字符串。把它放在配置文件中。绝大部分肯定不会在互联网上发布。