C#,MySQL对象引用未设置为对象错误的实例

本文关键字:对象 错误 实例 设置 MySQL 对象引用 | 更新日期: 2023-09-27 17:59:57

我正在做一个C#项目,它从一个结构如下的文本文件中读取:The Godfather,1972,Drama,R,Braveheart,1995,Action,R等等

然后,它意味着将其输入MySql数据库,但当我单击上传按钮时,我会得到"对象引用未设置为对象实例"。为什么会这样?

public partial class Form1 : Form
{
    MySqlConnection mcon = new MySqlConnection("datasource=localhost;port= 3306;username= root;password=");
    MySqlCommand mcd;
    MySqlDataReader mdr;
    string s;
    public Form1()
    {
        InitializeComponent();
    }
    private void buttonUpload_Click(object sender, EventArgs e)
    {
        string[] lines = File.ReadAllLines(@"C:''Users'Owner'Desktop'moviedata.txt");
        foreach (var line in lines)
        {
            var data = line.Split(new[] { ',' }, 4);
            string title = data[0].Trim();
            int year = int.Parse(data[1].Trim());
            string genre = data[2].Trim();
            string rating = data[3].Trim();
            recordMovie(title, year, genre, rating);
        }
    }
    private void recordMovie(string title, int year, string genre, string rating)
    {
        try
        {
        mcon.Open();
        mcd.CommandText = @"INSERT INTO movies (title, year, genre, rating) VALUES (@title, @year, @genre, @rating)";
        mcd.Parameters.AddWithValue("@title", title);
        mcd.Parameters.AddWithValue("@year", year);
        mcd.Parameters.AddWithValue("@genre", genre);
        mcd.Parameters.AddWithValue("@rating", rating);
        mcd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            mcon.Close();
        }
    }
}

C#,MySQL对象引用未设置为对象错误的实例

您不应该将MySqlCommand指定为连接字符串。将您的代码添加到此行

mcd= new MySqlCommand("INSERT INTO movies (title, year, genre, rating) VALUES (@title, @year, @genre, @rating)", mcon);

更多详细信息请参阅此链接

http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL