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();
}
}
}