在有人否决我的问题之前,我想说这是我第一次在 C# 中使用类,我已经做了很多研究,但我仍然遇到错误。新手来了
我试图将 Insert、Delete、Update 和 Count 语句放在类文件中,以便我的代码整洁。
这是我制作的类文件(当然是在研究的帮助下):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;
using System.Windows.Forms;
namespace classlib
{
public class DBConnect
{
private static MySqlConnection mycon;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "localhost";
database = "restaurantdb";
uid = "user";
password = "root";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
mycon = new MySqlConnection(connectionString);
}
private static bool OpenConnection()
{
try
{
mycon.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
private static bool CloseConnnection()
{
try
{
mycon.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public static void Insert(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Update(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = mycon;
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Delete(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static int Count(string query)
{
int count = -1;
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
count = int.Parse(cmd.ExecuteScalar() + "");
CloseConnnection();
return count;
}
else
{
return count;
}
}
}
}
我只是在尝试某种形式的计数方法。这是我的代码:
MessageBox.Show("NUMBER OF ACCOUNTS IN DATABASE = "+ DBConnect.Count("SELECT count(*) FROM usersettingsdb") +"", "CONFIRMATION");
但是我在类文件上的OpenConnection()
方法上得到了这个错误mycon.Open()
:
Object reference not set to an instance of an object.
如何删除上述错误并通过像这样调用它来访问方法DBConnect.MethodName()
?
我对类一无所知,但我真的很想知道如何创建自己的函数/方法以保持代码整洁。