Error Connecting to Database in VB - c#

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

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

Related

propbem the mysqlconnection when using public variable in class level

I have c# class that make me to connect the database and make some operations on it.
#region Var
private readonly string DbPath;
public MySqlConnection DbConn;
#endregion
#region Constructor
public ClsDb()
{
DbPath = "SERVER= " + Db.Default.ServerName + "; " +
"DATABASE= " + Db.Default.DbName + "; " +
"UID= " + Db.Default.UserName + "; " +
"PWD= " + Db.Default.UserPass + "; " +
"PORT= " + Db.Default.ThePort+"; sslmode=none";
DbConn = new MySqlConnection(DbPath);
}
#endregion
as you see I declared (mysqlconnection) :
DbConn = new MySqlConnection(DbPath);
so after that I check the connection:
public bool CheckConn()
{
try
{
if (DbConn.State == ConnectionState.Open)
{
DbConn.Close();
}
if (DbConn.State == ConnectionState.Closed)
{
DbConn.Open();
return true;
}
return false;
}
catch
{
MessageBox.Show(Msgs.Default.ConnErr,
Settings.Default.ComName,
MessageBoxButtons.OK,
MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
return false;
}
}
and after that I'm trying to execute SQL statement by method:
public void RunSql(string xSql, MySqlParameter[] xPar)
{
//...
MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);
// ....
if (xPar != null)
{
xCmd.Parameters.AddRange(xPar);
}
//...
xCmd.ExecuteNonQuery();
}
but it gives me the following error:
"Connection must be valid and open."
when I checked the code by the breakpoints I got that everything is ok and it opens the connection very well but when it execute (public void RunSql) and exactly on the line:
MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);
when I tried to solve it I changed (public MySqlConnection DbConn) to (public Static MySqlConnection DbConn) and it worked but I needed to know why that happened although I declared the variable as public?? and why it worked when I changed to Static??
I'm using my own class for this. In it isn't necessary to close the connection because uses the 'using'.
The class:
Connection (return open connection)
public static MySqlConnection GetConn()
{
MySqlConnection conn = new MySqlConnection(ConnString);
try
{
conn.Open();
}
catch (MySqlException)
{
throw;
}
return conn;
}
Insert Commands (accept params)
public static int InsertSqlCommand(string db, params (string param, object value)[] listParams)
{
using (MySqlConnection conn = GetConn())
{
using (MySqlCommand cmd = new MySqlCommand(db, conn))
{
foreach ((string dbLocal, object incremento) in listParams)
cmd.Parameters.AddWithValue(dbLocal, incremento);
int linhasAfetadas = cmd.ExecuteNonQuery();
return linhasAfetadas;
}
}
}
Select Command (accept params)
public static DataTable SelectSqlCommand(string db, params (string param, object value)[] listParams)
{
DataTable dttoken = new DataTable();
using (MySqlConnection conn = GetConn())
{
using (MySqlCommand cmd = new MySqlCommand(db, conn))
{
foreach ((string dbLocal, object incremento) in listParams)
cmd.Parameters.AddWithValue(dbLocal, incremento);
using (MySqlDataAdapter sqlDA = new MySqlDataAdapter(cmd))
{
sqlDA.Fill(dttoken);
return dttoken;
}
}
}
}

asp.net login function to database

Hello i want to make a log in function in asp.net but i have no clue on what to do. i have taken the login toolbox and place it, what do i do next
void Fillcombo() {
string constring = "datasource=localhost;username=username;password=password";
string Query = "select * from hotel";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
and here is the login
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
}
I am going to build onto Nasir's earlier response with a simple database routine.
I have written this using SQL Server, so some translation may be needed. I have written this based on the saved password has been hashed. Hashing is your responsibility!
private bool IsAuthenticate(string username,string password) {
string constring = "datasource=localhost;username=username;password=password";
string Query = "SELECT Count(*) FROM hotel WHERE (UserLogin = #UserLogin) AND (UserPassword = #UserPassword)";
int RecordsMatched;
string UserLogin = username;
string UserPassword = SomeHashFunction(password)
using (SqlConnection conDataBase = new SqlConnection(constring)) {
using (SqlCommand cmd = new SqlCommand(Query, conDataBase)) {
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserLogin", UserLogin);
cmd.Parameters.AddWithValue("#UserPassword", UserPassword);
try {
conDataBase.Open();
RecordsMatched = (int)cmd.ExecuteScalar();
}
catch (Exception ex) {
RecordsMatched = -1;
Console.Write(ex);
// your error handling here
}
finally {
conDataBase.Close();
// your cleanup here
}
}
}
// Logic for RecordsMatched
// -1: An error occurred
// 0: UserLogin and/or UserPassword did not match
// 1: Authenticated
// 2+: You have multiple users with same credentials
return (RecordsMatched == 1);
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string userName = Login1.UserName;
string password = Login1.Password;
bool result = IsAuthenticate(userName, password);
if ((result))
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
protected bool IsAuthenticate(string username,string password)
{
// implement this method according to your database..
}

C# SQL Server Class Connection String from a text file [error Instance failure]

I save connection string in a text file, like this :
koneksi.txt
Data Source=GGL-TBGIT-PC02\\SQLEXPRESS; Initial Catalog=db_timbangan;user=sa;password=GGL654321
and this my class connection
class Koneksi
{
public System.Data.SqlClient.SqlConnection GetConn()
{
string path;
TextReader tr = new StreamReader(#"D:\PROJECT\2.0 TIMBANGAN\TIMBANGAN\koneksi.txt");
path = tr.ReadLine();
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = path;
return conn;
}
}
this my login
Koneksi konn = new Koneksi();
public Login()
{
InitializeComponent();
this.AcceptButton = button1;
}
private Boolean statusLogin(string username, string password)
{
System.Data.SqlClient.SqlConnection conn = konn.GetConn();
conn.Open();
string sql = "select * from tbl_login where username='" + username + "' AND password='" + password + "'";
SqlCommand command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader["username"].ToString() == username && reader["password"].ToString() == password)
{
return true;
}
}
conn.Close();
return false;
}
when I tried to log in, the error Instance failure at conn.Open()
how to fix it ?
Try using the connection string with only one \
Data Source=GGL-TBGIT-PC02\SQLEXPRESS; Initial Catalog=db_timbangan;user=sa;password=GGL654321
Additionally, you should be using a using for your SQL connection.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//read here
connection.Close();
}

Cannot implicity convert type error

Trying to fill Combobox with data from a database and I'm using ExecuteReader as below, but when I try to instantiate my connection it shows me the error
Cannot implicitly convert type error
My DBConnect class code:
public class DBConnect
{
private SqlConnection connection;
private string servername = "10.1.76.109,1433";
private string database = "EngLib";
private string dbuser;
private string userpassword;
public DBConnect()
{
}
public void doDBConnect(string dbuserform, string userpasswordform)
{
dbuser = dbuserform;
userpassword = userpasswordform;
}
public void Initialize()
{
}
public bool openConnection()
{
string connectionString;
connectionString = "Server=" + servername + ";Database=" + database + ";user id=" + dbuser + ";Password=" + userpassword;
Console.WriteLine(connectionString);
connection = new SqlConnection(connectionString);
try
{
connection.Open();
return true;
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Não é possível contactar o servidor. Entre em contato com o administrador");
break;
case 18456:
MessageBox.Show("Usuário/Senha inválidos, tente novamente");
break;
}
return false;
}
}
My form code:
{
public Form2()
{
InitializeComponent();
}
public void Form2_Load(object sender, EventArgs e)
{
SqlDataReader rdr = null;
DBConnect sqlConnection;
sqlConnection = new DBConnect();
sqlConnection.doDBConnect(dbuserform: "usertest", userpasswordform: "usertest");
{
try
{
{
sqlConnection.openConnection();
SqlCommand sqlCmd;
sqlCmd = new SqlCommand("SELECT Material FROM EngLib");
sqlCmd.Connection = sqlConnection;
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
comboBox1.Items.Add(sqlReader["Material"].ToString());
}
sqlReader.Close();
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
}
}
}
}
The user and password in the code is just temporary.
I think the problem is here:
DBConnect sqlConnection;
SqlCommand sqlCmd;
sqlCmd.Connection = sqlConnection;
SqlCommand expects that Connection is of type SqlConnection, but you are assigning your own class DBConnect.
Possible fixes:
Expose the connection property on DBConnect and use it.
Inherit DBConnect from SqlConnection.
Use SqlConnection directly.
An additional note: you are not disposing the SqlConnection inside your DBConnect class, which can lead to StackOverflowException. You should implement IDisposable.

check if user exists in my database

I have a c# login forum that has two text-boxes
1.username
2.password
I am trying to check if the user exists in my Oracle database or not. If so, I want it to do something (like call another forum, etc...), but I'm getting an error msg that says I have a missing expression. Whats wrong with it?
private void button1_Click(object sender, EventArgs e)
{
isUserExist(textBox1.Text,textBox2.Text);
}
public bool isUserExist(string username,string password)
{
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statementcmd = "SELECT * FROM register_user Where UserName=#username";
OracleConnection conn = new OracleConnection(connstring);
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = statementcmd;
cmd.Parameters.Add("#username", username);
if (conn.State != ConnectionState.Open)
{
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (!reader.HasRows)
{ MessageBox.Show("User Name Not Found"); }
if (!password.Equals(reader["password"].ToString()))
MessageBox.Show("Incorrect Password");
reader.Close();
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
You need to call the Read method on the DataReader before trying to access the properties.
if (reader.Read())
{
// Do stuff
}
Good luck!
1. you need to assign parameters before assigning commandstring to the CommandText.
2. you need to call Read() OracleDataReader object reader before accessing the records.
3. you should return true when true only when user is found.(in second if condition open curly braces is missing).
4. you can use using{} block for all IDisposable Implemented classes in your program so that their objects disposal will be taken care.(so you don't need to call Close() on Connection or Command objects)
Complete Solution:
public bool isUserExist(string username,string password)
{
bool status=false;
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statementcmd = "SELECT * FROM register_user Where [UserName]=#username";
using(OracleConnection conn = new OracleConnection(connstring))
{
using(OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.Parameters.Add("#username", username);//add parameters before assigning it to CommandText
cmd.CommandText = statementcmd;
if (conn.State != ConnectionState.Open)
{
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (!reader.Read())
{ MessageBox.Show("User Name Not Found"); }
if (!password.Equals(reader["password"].ToString()))
{
status=true;
MessageBox.Show("Incorrect Password");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
status=false;
}
return status;
}

Categories

Resources