在调用read()之前无效尝试访问字段为什么我会收到此错误 [英] Invalid attempt to access a field before calling read() why do I get this errors

查看:79
本文介绍了在调用read()之前无效尝试访问字段为什么我会收到此错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我得到这个错误?我无法从数据库中获取信息



我收到此异常错误:



Why exactly am i getting this Errors? I cannot fetch information from the Database

And i am getting this Exception Error :

Invalid attempt to access a field before calling Read()





我的代码看起来像这样





My code Looks like this

private void button1_Click(object sender, EventArgs e)
{
    string constring = ConfigurationManager.ConnectionStrings["MySQLDatabaseConnection"].ConnectionString;
    string query = "select * from vms_db.final_appointments where visitor_name = '"+visitor_name.Text+"'";
    using (MySqlConnection con = new MySqlConnection(constring))
    {
        con.Open();
        try
        {
            using (MySqlCommand cmd = new MySqlCommand(query, con))
            {
                using (MySqlDataReader rdr = cmd.ExecuteReader())
                {
                    try
                    {
                        visit_date.Text = (rdr["visit_date"].ToString()); <-----Error on this Line
                        visitor_name.Text = (rdr["visitor_name"].ToString());
                        organization.Text = (rdr["organization"].ToString());
                        city.Text = (rdr["city"].ToString());
                        signin_time.Text = (rdr["signin_time"].ToString());
                        vehicle_number.Text = (rdr["vehicle_number"].ToString());
                        visit_type.Text = (rdr["visit_type"].ToString());
                        reason.Text = (rdr["reason"].ToString());
                        id_type.Text = (rdr["id_type"].ToString());
                        person_visit.Text = (rdr["person_visit"].ToString());
                        byte[] imagebyte = (Byte[])(rdr["passport"]);
                        MemoryStream ms = new MemoryStream(imagebyte);
                        pictureBox1.Image = Image.FromStream(ms);
                        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                        this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }

            }
            con.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}





我尝试过:



删除并替换此行



What I have tried:

Removing and replacing this line

visit_date.Text = (rdr["visit_date"].ToString())

仍然给出错误。

推荐答案

添加此



add this

if (rdr.Read()) // read
{
visit_date.Text = (rdr["visit_date"].ToString()); 
.
.
.





参考 SqlDataReader.Read方法(System.Data.SqlClient) [ ^ ]


SqlDataReader一次返回一行数据,当你通过调用Read明确告诉它时,它只知道何时更改行

An SqlDataReader returns data a row at a time, and it only knows when to "change the row" when you explicitly tell it to do that by calling Read:
using (MySqlDataReader rdr = cmd.ExecuteReader())
{
    try
    {
        if (rdr.Read())
        {
            visit_date.Text = (rdr["visit_date"].ToString());

Read方法获取下一行,如果有可用则返回true。



但不要那样做!

永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。改为使用参数化查询。



连接字符串时会导致问题,因为SQL会收到如下命令:

The Read method fetches the next row, and returns true if one is available.

But don't do it like that!
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:

SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

就SQL而言,用户添加的引号会终止字符串,并且您会遇到问题。但情况可能更糟。如果我来并改为输入:x'; DROP TABLE MyTable; - 然后SQL收到一个非常不同的命令:

The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:

SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

哪个SQL看作三个单独的命令:

Which SQL sees as three separate commands:

SELECT * FROM MyTable WHERE StreetAddress = 'x';

完全有效的SELECT

A perfectly valid SELECT

DROP TABLE MyTable;

完全有效的删除表格通讯和

A perfectly valid "delete the table" command

--'

其他一切都是评论。

所以它确实:选择任何匹配的行,从数据库中删除表,并忽略其他任何内容。



所以总是使用参数化查询!或者准备好经常从备份中恢复数据库。你定期做备份,不是吗?

And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?


这篇关于在调用read()之前无效尝试访问字段为什么我会收到此错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆