【问题标题】:Unable To Find Column无法找到列
【发布时间】:2014-03-15 13:44:56
【问题描述】:

为什么下面的说法是错误的?

    static void Main(string[] args)
    {
        string connString = "Server=localhost;Port=3306;Database=connection;Uid=root;password=;";
        MySqlConnection conn = new MySqlConnection(connString);
        MySqlCommand command = conn.CreateCommand();
        command.CommandText = "Select number from user where id=1";
        try
        {
            conn.Open();
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
        MySqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(reader["text"].ToString());

        }
        Console.ReadLine();
    }

这是我的数据库: 数据库名称:连接 表名:用户

number: 18.81
id: 1

【问题讨论】:

  • 您加载了一个名为 number 的列,然后搜索了一个名为 text 的列?
  • 但是我不明白返回 FALSE 的语句是什么。就像现在一样,或者您没有任何 ID=1 的记录,否则此代码将在 read["text"] 代码处引发异常。

标签: c# mysql sql .net


【解决方案1】:

您当前仅从数据库中选择 number 字段,但尝试从结果集中读取 text 字段。在 select 语句中添加 text 字段(如果您想从数据库中获取文本):

command.CommandText = "Select text from user where id=1";

或者从结果集中读取number(我认为你需要这个解决方案,如果你描述的表结构是正确的):

Console.WriteLine(reader["number"].ToString());

【讨论】:

    【解决方案2】:

    使用参数化查询,您的查询对 SQL 注入开放。

    在您的 sql 选择语句 Select number from user where id=1 您正在选择数字,但在阅读器中您试图访问错误的文本,请尝试此代码。

    static void Main(string[] args)
    {
        string connString = "Server=localhost;Port=3306;Database=connection;Uid=root;password=;";
        MySqlConnection conn = new MySqlConnection(connString);
        MySqlCommand command = conn.CreateCommand();
        command.CommandText = "Select number from user where id=@Id";
        command.Parameters.Add("@Id", SqlDbType.Int);
        command.Parameters["@Id"].Value = 1;
        try
        {
            conn.Open();
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
        MySqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(reader["number"].ToString());
    
        }
        Console.ReadLine();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多