0

I'm working on a C# project that reads from a text file that's structured like this: The Godfather,1972,Drama,R,Braveheart,1995,Action,R and so on.

Then it's meant to enter it into a MySql database, but when I click the upload button, I'm getting "object reference not set to an instance of an object". Why might that be?

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();
        }
    }
}
Adam Feoras
  • 47
  • 1
  • 7
  • `mcd` is null when you try to use it. Apart from this, do not use global variables, declare the required one directly in the function where you use it. You gain nothing in performance and you loose all in resource usage (not to mention bugs caused by forgotten open connections, parameters not cleared etc...) – Steve Jun 27 '15 at 13:18

1 Answers1

0

You should be not specify MySqlCommand to connection string. Add your code this line

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

More details to refer this link

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

Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32