简体   繁体   English

以下查询出了什么问题?

[英]What is wrong with the following query?

I have a table containing name, surname and email. 我有一个包含名称,姓氏和电子邮件的表格。 I want to retrieve them from the table and so i write: 我想从表中检索它们,所以我写:

if (LoginAs.SelectedValue == "Administrator")
{
    string result;
    string query = "Select * from AdminTable where ID='"+ idBox.Text +"'";
    cmd1 = new SqlCommand(query, con);
    result = Convert.ToString(cmd1.ExecuteScalar());

    Response.Redirect("Admin.aspx");
    //Admin user = new Admin(idBox.Text, "Active",  mail, firstName, LastName, passwordBox.Text);
}

The problem is, it only returns the name field of the specified row even though i wrote "Select *". 问题是,即使我写了“ Select *”,它也只返回指定行的名称字段。 What is wrong here? 怎么了

You must try ExecuteReader() instead of using ExecuteScalar() 您必须尝试ExecuteReader()而不是使用ExecuteScalar()

ExecuteScaler is used in situation where we have to read a single value.eg: ExecuteScaler用于必须读取单个值的情况。例如:

select count(*) from tablename. 从表名中选择count(*)。

while

ExecuteReader is used for any result set with multiple rows/columns (eg, SELECT * from TableName) ExecuteReader用于具有多个行/列的任何结果集(例如SELECT * from TableName)

ExecuteScalar returns just the first column of the first row, and ignores the rest. ExecuteScalar仅返回第一行的第一列,而忽略其余部分。

So you should use ExecuteReader method. 因此,您应该使用ExecuteReader方法。 An example from MSDN: 来自MSDN的示例:

using (SqlConnection connection = new SqlConnection(
           connectionString))
{
    connection.Open();

    SqlCommand command = new SqlCommand(queryString, connection);
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine(String.Format("{0}", reader[0]));
    }
}

Note that the while (reader.Read()) checks whether your query returned (more) results and positions the cursor on the next record, that you can then read. 请注意, while (reader.Read())检查查询是否返回了(更多)结果,并将光标定位在下while (reader.Read())记录上,然后您可以读取该记录。 This example prints the first column's value. 本示例打印第一列的值。
The using statement makes sure the connection is closed after use, whatever happens. using语句可确保使用后关闭连接,无论发生什么情况。

Also, don't build your query directly with input from the user (such as the value of a TextBox), use parameters instead to prevent SQL injection attacks. 另外,不要直接使用用户输入(例如TextBox的值)来构建查询,而应使用参数来防止SQL注入攻击。

Sample code: 样例代码:

 string myQuery="Select * from AdminTable where ID=@myid";
 SqlCommand cmd=new SqlCommand(myQuery,conn);
 cmd.Parameters.AddWithValue("@myid", value);
 conn.Open();
 SqlDataReader dreader;
 dreader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
 while (dreader.Read())
 {
    string Value1= dreader["COl1"].ToString();
    string Value2= dreader["COl2"].ToString();
 }  
 dreader.Close(); 

Always use parameterized Query 始终使用参数化查询

您可以尝试使用cmd1.ExecuteReader()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM