我正在使用SQL Datareader来填充.aspx页面中的文本框。我的下面
#region "[--------Function To Fill Up All TextBox---------]>"
public void FillTextBox(string Sqlstring)
{
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL Connection String"].ConnectionString);
SqlDataReader MyDataReader = null;
SqlCommand MyOleDbCommand = new SqlCommand();
MyOleDbCommand.Connection = (Conn);
Conn.Open();
MyOleDbCommand.CommandText = Sqlstring;
MyDataReader = MyOleDbCommand.ExecuteReader();
try
{
while (MyDataReader.Read())
{
txtuniv.Text = (MyDataReader[0].ToString());
txtcollrno.Text = (MyDataReader[1].ToString());
/*txtLastName.Text = (MyDataReader[2].ToString());
txtClass.Text = (MyDataReader[3].ToString());
txtSession.Text = (MyDataReader[4].ToString());
txtobt.Text = (MyDataReader[5].ToString());
txttot.Text = (MyDataReader[6].ToString());
*/
}
}
catch (System.Exception err)
{
MyDataReader.Close();
Conn.Close();
Conn.Dispose();
}
}
#endregion
在PageLoad()Eveent
中 protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = User.Identity.Name.ToString();
string SqlStr = null;
SqlStr = "Select * from TB_User where UserID=" + Label1.Text;
FillTextBox(SqlStr);
}
我有表TB_User,列UserID&密码。它有价值测试1& test1分别。但它会给出以下错误。
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'test1'.
Source Error:
Line 40: Conn.Open();
Line 41: MyOleDbCommand.CommandText = Sqlstring;
Line 42: MyDataReader = MyOleDbCommand.ExecuteReader();
Line 43: try
Line 44: {
请帮助
答案 0 :(得分:2)
用户ID必须在查询中使用'
进行封装。
SqlStr = "Select * from TB_User where UserID='" + Label1.Text + "'";
答案 1 :(得分:2)
尝试更改以下内容:
SqlStr = "Select * from TB_User where UserID=" + Label1.Text;
为:
SqlStr = string.Format("Select * from TB_User where UserID='{0}'",Label1.Text);
在原始版本数据库中,您认为您正在寻找一个列Test1而不是与值'Test1'进行比较
答案 2 :(得分:2)
您忘记在参数周围添加单引号。
"Select * from TB_User where UserID='" + Label1.Text +"'";
using-statement
进行连接(以及实施IDisposable
的所有其他内容)。 Dispose也将关闭连接,即使出错也会using
。以下是一个例子:
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL Connection String"].ConnectionString)) {
var sql = "Select * from TB_User where UserID=@UserID";
using (var cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("@UserID", Label1.Text);
con.Open();
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// ...
}
}
}
}
答案 3 :(得分:1)
试试这个,引用userID
SqlStr = "Select * from TB_User where UserID='" + Label1.Text + "'";
考虑在您的代码中使用参数化查询 - 避免SQL注入攻击,并使您免受可能损害您的SQL语法的偶然字符
SqlStr = "Select * from TB_User where UserID=@UserID";
答案 4 :(得分:1)
从安全角度来看,您的代码很糟糕。这行要求进行Sql注入:
SqlStr = "Select * from TB_User where UserID=" + Label1.Text;
此外,您应该将对象置于finally块中,而不是catch中,因为这样您只有在出现问题时才会释放资源。
第三个也是最后一个,在查询中指定列名称并告诉我们它是如何运行的。
答案 5 :(得分:0)
检查列名是否正确拼写。