从查询中检测到SQL无效的列名称

极小

我尝试运行代码,但不知道查询出了什么问题。因为它一直说无效的列名,所以当我尝试从该列检索数据时。列名与数据库中的列名匹配。它连接良好,因为它已连接到登录表单,在表单中它检测到其他给定的密码和名称。我使用的是基于搜索文本框。

private void btnSearch_Click(object sender, EventArgs e)
{   
    SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDetailConnectionString"].ToString());

    try
    {
        cnn.Open();
        SqlCommand command = new SqlCommand();
        command.Connection = cnn;
        string query = "SELECT *FROM AffiliatedRegister WHERE Username=" + txtUser.Text + "";
        command.CommandText = query;
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
          ---[Converting String from db /Insert to textboxes]---
        }
        cnn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error" + ex);
    }
}
伊戈尔

您的语句出错了,因为您没有将字符串用引号引起来,因此Sql将其插入对象而不是字符串。话虽这么说,您应该使用参数而不是字符串连接。

  1. 使用参数
  2. 将您的SqlConnection包装在using块中
  3. 您应该在SELECT语句中指定列顺序,不要使用*。
  4. 除非您知道如何从异常中恢复,否则不要吞下异常

更新代码

private void btnSearch_Click(object sender, EventArgs e)
{
    // use ConnectionString property
    // wrap in using block
    using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDetailConnectionString"].ConnectionString))
    {
        try
        {
            SqlCommand command = new SqlCommand();
            command.Connection = cnn;
            // use parameters
            // avoid *, specify columns instead
            string query = "SELECT * FROM AffiliatedRegister WHERE Username= @userName";
            command.CommandText = query;
            // use parameters, I assumed the parameter type and length - it should be updated to the type and length specified in your table schema
            command.Parameters.Add(new SqlParameter("@userName", SqlDbType.VarChar, 200) {Value = txtUser.Text });

            // open as late as possible
            cnn.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                // ---[Converting String from db / Insert to textboxes]-- -
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex); 

            // do not swallow the exception unless you know how to recover from it
            throw;
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章