我决定创建一个连接到MySQL服务器的应用程序,但似乎我的代码存在问题。
public partial class FRM_LOGIN : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public FRM_LOGIN()
{
InitializeComponent();
}
private void BTN_CONNECT_Click(object sender, EventArgs e)
{
server = "localhost";
database = "databasenamehere";
uid = "root";
password = "root";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";old guids=true;";
connection = new MySqlConnection(connectionString);
try
{
if (TXTBOX_USERNAME.Text == "" || TXTBOX_PASSWORD.Text == "")
{
MessageBox.Show("Please fill up all the fields of the login form.");
}
else
try
{
connection.Open();
MySqlCommand com = new MySqlCommand("SELECT * FROM tbl_login WHERE (user_id=@id AND user_password=@pwd)", connection);
com.Parameters.Add(new MySqlParameter("id", SqlDbType.NVarChar)).Value = this.TXTBOX_USERNAME.Text;
com.Parameters.Add(new MySqlParameter("pwd", SqlDbType.NVarChar)).Value = this.TXTBOX_PASSWORD.Text;
MySqlDataReader myReader = com.ExecuteReader();
myReader.Read();
if (myReader.HasRows == true)
{
MessageBox.Show("Login Successfull", "Login Information");
this.Hide();
FRM_MAIN frm_main = new FRM_MAIN();
frm_main.Show();
}
else
{
MessageBox.Show("Invalid User Name or Password", "Hello", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
connection.Close();
}
catch (MySqlException ex)
{
throw;
}
}
catch (MySqlException ex)
{
{
case 0:
MessageBox.Show(ex.Message);
MessageBox.Show("Cannot connect to server. Contact administrator", " Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case 1045:
MessageBox.Show(ex.Message);
MessageBox.Show("Invalid username/password, please try again");
break;
}
}
}
}
很多是来自这里和一些教程的各种答案的补丁工作,所以请不要在这里判断,完成新手。
因此,大多数人都可以说,我有一个带有2个文本框和一个按钮的表单。我的目标是通过查找凭据是否在表tbl_login中来验证用户身份。如果有结果,请关闭form1打开另一个表单。
我现在的问题是每次点击按钮都会抛出异常。
未处理的类型' System.FormatException'发生在 mscorlib.dll中
{"输入字符串的格式不正确。"}
它指出了
MySqlDataReader myReader = com.ExecuteReader();
为什么这种情况不断发生?任何帮助将不胜感激。