所以我试图连接到MySQL数据库来检索信息,但我得到了空引用异常..
这是我的代码:
logIn.cs
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 StoreInventory
{
public partial class logIn : Form
{
public logIn()
{
InitializeComponent();
dbObject mysqlcon = new dbObject();
mysqlcon.connectToDb();
}
private void confirmButton_Click(object sender, EventArgs e)
{
dbObject db = new dbObject();
MySqlConnection con;
string username = userBox.Text;
string password = pwBox.Text;
string query = "SELECT * FROM `users` WHERE username='" + username + "' AND password='" + password + "'";
con = new MySqlConnection(db.connection.ConnectionString);
con.Open();
MySqlDataReader reader = null;
MySqlCommand cmd = new MySqlCommand(query, con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader.GetString(0));
}
}
}
}
dbObject.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace StoreInventory
{
class dbObject
{
public MySqlConnection connection;
private string server;
private string database;
private string username;
private string pasword;
public void connectToDb()
{
string server = "localhost";
string database = "shopdb";
string username = "root";
string pasword = "";
string connectionString;
connectionString = "SERVER=" + server +";" + "DATABASE=" +
database + ";" + "UID=" + username + ";" + "PASSWORD=" + pasword + ";";
try
{
connection = new MySqlConnection(connectionString);
connection.Open();
}
catch (MySqlException err)
{
MessageBox.Show("Error: " + err, "Fatal error");
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
}
}
我做错了什么?我花了半个小时试图解决它,但我无法找到它...抱歉,如果它是一个愚蠢的错误,我还是新的。
提前致谢。