C#查询数据库--ExecuteReader方法的使用

在做数据库的查询过程中,使用方法ExecuteReader,其返回结果为MySqlDataReader,由于参考的信息有误,走了好长时间的弯路,记录下来;

		string connectionStr = "server=localhost;uid=root;password=;database=db_family";
        string sqlContent = "select * from t_user";

        MySqlConnection sqlConnection = null;
        MySqlDataReader reader = null;
        try
        {
            sqlConnection = new MySqlConnection(connectionStr);
            sqlConnection.Open();
            MySqlCommand command = new MySqlCommand(sqlContent,sqlConnection);
            reader = command.ExecuteReader();

            while (reader.Read())
            {
                if (reader.HasRows)
                {
                    Console.WriteLine(reader.GetInt32(0) + ":" + reader.GetString(1) + ":" + reader.GetString(2));
                }
            }
        }
        catch (Exception exception)
        {
            throw new Exception(exception.Message);
        }
        finally
        {
            reader.Close();
            sqlConnection.Close();
        }

猜你喜欢

转载自blog.csdn.net/qq_43026206/article/details/86998896