我正在使用visual studio中的登录功能,我将下面的代码连接到数据库。我无法弄清楚我在这里做错了什么,但我收到了错误databaseConn.db_connection() is a method which is not valid in the given context.
using MySql.Data.MySqlClient;
namespace Connection
{
static class databaseConn
{
static public void db_connection()
{
try
{
var conn = "Server=myhomeserver.net;Database=addonInstaller;Uid=root;Pwd=g278535814;";
var connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
MessageBox.Show("Could not Connect to Server");
}
}
}
}
namespace UserFunctions
{
static class Users
{
static public void LoginFunc(String username, String password)
{
CheckUsername(username, password);
}
static public void CheckUsername(String username, String password)
{
Connection.databaseConn.db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM users WHERE username=" + username + "";
cmd.Connection = Connection.databaseConn.db_connection.Open(); //This is my error area.
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
MessageBox.Show("Continue to Login");
}
else
{
MessageBox.Show("Username Not Found");
}
}
}
}
答案 0 :(得分:3)
您已将db_connection
定义为静态函数,而非属性,因此您无法使用db_connection.Open()
。
您可以尝试修改db_connection
以返回connection object
,或将其存储为静态属性
<强> databaseConn 强>:
static public MySqlConnection db_connection()
{
try
{
var conn = "Server=myhomeserver.net;Database=addonInstaller;Uid=root;Pwd=g278535814;";
var connect = new MySqlConnection(conn);
connect.Open();
return connect;
}
catch (MySqlException e)
{
MessageBox.Show("Could not Connect to Server");
}
return null;
}
用户强>:
var conn = Connection.databaseConn.db_connection();
if (conn != null)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM users WHERE username=" + username + "";
cmd.Connection = conn;
MySqlDataReader login = cmd.ExecuteReader();
... ...