I'm using C# + MySql + MySql connector to enter information into MySql database (via Xampp), And get the entered data back into a DataGridView.
When retrieving back the data, I get exceptions: (1) "SELECT command denied to user ''@'localhost' for table 'students'" and (2) "Host 'DELL-KL2001' is not allowed to connect to this MySQL server". The 2nd exception occurs when I run the code while connected to the Net. I tried similar question that being answered, though I'm not able to detect my coding error. Could you guys please look at my code and give a tip about the error in my code? Much appreciated.
P.S. I've not typed erroneous DB or table names like the case in some other questions I've read.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySqlBasics
{
public partial class FrmRegList : Form
{
public FrmRegList()
{
InitializeComponent();
}
string MySqlConnectionString;
private void FrmRegList_Load(object sender, EventArgs e)
{
string MySqlConnectionString = "Server=localhost;Database=student_reg.students;Uid=root;Pwd=pass";
}
private void btnEnter_Click(object sender, EventArgs e)
{
int mobileNo;
string mobile = tbMobNo.Text;
int.TryParse(mobile, out mobileNo);
MySqlConnection sqlConnection = new MySqlConnection(MySqlConnectionString);
MySqlCommand sqlCmd;
sqlConnection.Open();
try
{
sqlCmd = sqlConnection.CreateCommand();
sqlCmd.CommandText = "INSERT INTO students(Id, Name, MobileNo)VALUES(@Id, @Name, @MobileNo)";
sqlCmd.Parameters.AddWithValue("@Id", int.Parse(tbId.Text));
sqlCmd.Parameters.AddWithValue("@Name", tbName);
sqlCmd.Parameters.AddWithValue("@MobileNo", mobile);
MySqlDataReader mySqlReader;
mySqlReader = sqlCmd.ExecuteReader();
}
catch (Exception)
{
MessageBox.Show("Error: btnEnter_Click()");
}
LoadDataFromForm();
}
private void LoadDataFromForm()
{
MySqlConnection sqlConnection = new MySqlConnection(MySqlConnectionString);
sqlConnection.Open();
//try
{
MySqlCommand sqlCmd = sqlConnection.CreateCommand();
sqlCmd.CommandText = "SELECT * FROM student_reg.students";
MySqlDataAdapter sqlAdapter = new MySqlDataAdapter(sqlCmd);
DataSet sqlDataset = new DataSet();
sqlAdapter.Fill(sqlDataset);
dGridRegs.DataSource = sqlDataset.Tables[0].DefaultView;
}
//catch (Exception ex)
{
//MessageBox.Show("Error: LoadDataFromForm() " + ex.Message);
}
}
private void btnDebug_Click(object sender, EventArgs e)
{
LoadDataFromForm();
}
}
}