Morgan Green Morgan Green - 2 months ago 11
C# Question

Error Connecting to Database in VB

I'm working on a login function in visual studio, I have my code listed below to connect to the database. I can't figure out what I'm doing wrong here, but I get the error

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");
}

}
}
}

Answer

You have define the db_connection as a static function, not a property, so that you can't use db_connection.Open().

You can try to modify your db_connection to return the connection object, or store it as static property

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;
}

Users:

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();
    ... ...