MySQL C# value inserting and connection.open() is not working properly - c#

I am trying to insert values in my database but unfortunately i am getting the same error again and again which i have shown in the picture(Please see the picture here: http://1.bp.blogspot.com/-oCH03jEnrdM/Uua4U9ddQZI/AAAAAAAABh0/BncJe0mHqQM/s1600/Capture.PNG) when i click the button. The error is somewhere in my Connection i think so but i am newbee therefore i dont have much idea about this error please help me in sorting out:
Here is my code:
public partial class Test : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Test()
{
InitializeComponent();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "ADC";
uid = "**********";
password = "********";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//EndDatabase
//Creating Connection
private bool OpenConnection()
{
try
{
connection.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;
case 1062:
MessageBox.Show("Duplicate Entry. Please try again with different cardentials");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//End Connection
private void Test_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var Pin = "1124";
var Sq= "What is your Name?";
var Sqa= "My Name is ";
var Bg= "B+";
var Int = "Programming";
var Skills= "Develepoment";
var webp = "xyz.com";
var addr= "DHA lahore";
var cnumber= "12324123";
string query = "INSERT INTO userprofilemoreinformation (Pin,SecurityQuestion,SecurityQuestionAnswer,BloodGroup,Interest,Skills,WebPage,Address,ContactNumber) VALUES(#Pin,#Sq,#Sqa,#Bg,#Int,#Skills,#webp,#addr,#cnumber)";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#Pin", Pin);
cmd.Parameters.AddWithValue("#Sq", Sq);
cmd.Parameters.AddWithValue("#Sqa", Sqa);
cmd.Parameters.AddWithValue("#Bg", Bg);
cmd.Parameters.AddWithValue("#Int", Int);
cmd.Parameters.AddWithValue("#Skills", Skills);
cmd.Parameters.AddWithValue("#webp", webp);
cmd.Parameters.AddWithValue("#addr", addr);
cmd.Parameters.AddWithValue("#cnumber", cnumber);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
}

It doesn't look like you ever call your Initialize method.
public Test()
{
InitializeComponent();
Initialize();
}

Related

Host xxxx is not allowed to connect to this MySql server and class issue

I am currently trying to learn MySQL with C# and I've been having some problems.
string currServer = w.server.Text;
string currDatabase = w.database.Text;
string currUser = w.uid.Text;
string currPassword = w.password.Text;
server = currServer;
database = currDatabase;
uid = currUser;
password = currPassword;
This here gives me the error That I'm not allowed to connect to that host. But when I use
server = "localhost";
database = "test";
uid = "root";
password = "test123";
I am able to connect to the server. I've tried to create a new MySQL user and been Googling around a bit.
And I also have this error when I want to access my Query class to run queries I've get the error: Connection must be valid or open.
When I use the same method in the db_connection class this does not appear.
Query.cs file:
public void insertToDatabase()
{
var db_connection = new db_connection();
string query = "UPDATE users SET facebook = 'TEST123' WHERE user_id=9";
MySqlCommand cmd = new MySqlCommand(query, db_connection.Connection);
cmd.ExecuteNonQuery();
Console.WriteLine("Command: " + query + " executed without errors.");
}
db_connection.cs file:
public class db_connection
{
/* ---- Database Variables for Connection ---- */
public MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public void Initialize(Window w)
{
string currServer = w.server.Text;
string currDatabase = w.database.Text;
string currUser = w.uid.Text;
string currPassword = w.password.Text;
server = "localhost";
database = "test";
uid = "root";
password = "test123";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
/* ---- Open connection to the database ---- */
public bool openConnection()
{
try
{
connection.Open();
Console.WriteLine("MySQL Connection opened without errors.");
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("Could not establish a connection to the server.");
break;
case 1045:
Console.WriteLine("Invalid username or password");
break;
}
return false;
}
}
public MySqlConnection Connection
{
get { return this.connection; }
}
/* ---- Closing the connection to the database ---- */
public bool closeConnection()
{
try
{
connection.Close();
Console.WriteLine("MySQL Connection shutdown without errors.");
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("Error: " + ex.Number);
return false;
}
}
/* ---- Closing connection and trying to re-connect ---- */
public bool refreshConnection()
{
try
{
connection.Close();
Console.WriteLine("Restarting...");
connection.Open();
Console.WriteLine("Connection re-established without errors.");
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("Error:" + ex.Number);
return false;
}
}

make a label static error : cannot access a non-static member of outer type 'windowsForm8.Form1' via nested Type 'windowsForm8.Form1.DBConnect'

Yo this is my first post here and i wanna know how to fix this problem in C#
so im tryin to connect to database and select information from it and those information will be displayed as a label ! easy,
so this is the error i get :
cannot access a non-static member of outer type 'windowsForm8.Form1'
via nested Type 'windowsForm8.Form1.DBConnect'
and this is the Code :
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 WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
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;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
please help me
,thanks :)
Move all your code from the class DbConnect yo your Form1 class. Then all of your methods have access to your form controls.
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 WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
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;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
Like this your code ahould be able to access the labels, so it should compile. It still doesn't do anything since none of the methods are called.
Edited this on my phone, so couldn't test the code.

Write into 2 table in same DB in 2 different background worker process

I have a winforms app which will write data into 2 different tables in same DB. My timer will count every one second. When the first machine is ready to give data, I will get it and write to the first table. When the machine 2 is ready as well, I will get it and write data to the second table. I put these two inserting processes in two different background worker processes. But I keep getting an error "ExecuteNonQuery requires an open and available Connection. The connection's current state is connecting." Below is my code.
private void timer1_Tick(object sender, EventArgs e)
{
readMachinewidth();
}
private void readMachinewidth()
{
if(M1 == "true")
{
backgroundWorker1.RunWorkerAsync();
}
if(M2 == "true")
{
backgroundWorker2.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (!oData.saveM1ProcessQty("M1", "M1"))
{
MessageBox.Show("M1 - Database Error");
return;
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (oData.saveM2ProcessQty("M2", "M2"))
{
MessageBox.Show("M2 - Database Error");
return;
}
}
May I know how I can fix it? How I can make the winforms can write data in two different tables in almost the same time in same database. I expect it is the connection open issue. But I can't figure out how to fix it. When write table 1 data the connection is open while at the same time the data for Machine 2 may be ready to write as well.
My data insertion function
public Boolean saveM1ProcessQty(string M1, string M1a)
{
try
{
string sSQL = "";
SqlCommand oCmd;
sSQL = "INSERT INTO xxx(M1, M1-1)VALUES('";
sSQL = sSQL + M1+ "','" + M1a+ "')";
oConn.ConnectionLocal.Open();
oCmd = new SqlCommand(sSQL, oConn.ConnectionLocal);
oCmd.ExecuteNonQuery();
oConn.ConnectionLocal.Close();
oCmd.Dispose();
return true;
}
catch(SqlException sqlex)
{
oConn.ConnectionLocal.Close();
Common.ErrorLog("M1 - " + sqlex.Message.ToString());
return false;
}
catch(Exception ex)
{
oConn.ConnectionLocal.Close();
Common.ErrorLog("M1 - " + ex.Message.ToString());
return false;
}
}
public Boolean saveM2ProcessQty(string M2, string M2a)
{
try
{
string sSQL = "";
SqlCommand oCmd;
sSQL = "INSERT INTO xxx(M1, M1-1)VALUES('";
sSQL = sSQL + M2+ "','" + M2a+ "')";
oConn.ConnectionLocal.Open();
oCmd = new SqlCommand(sSQL, oConn.ConnectionLocal);
oCmd.ExecuteNonQuery();
oConn.ConnectionLocal.Close();
oCmd.Dispose();
return true;
}
catch(SqlException sqlex)
{
oConn.ConnectionLocal.Close();
Common.ErrorLog("M2 - " + sqlex.Message.ToString());
return false;
}
catch(Exception ex)
{
oConn.ConnectionLocal.Close();
Common.ErrorLog("M2 - " + ex.Message.ToString());
return false;
}
}
My Connection class
public SqlConnection ConnectionLocal
{
get
{
if(_localConn == null)
{
string sconnstring =
ConfigurationManager.ConnectionStrings["local"].ToString();
_localConn = new SqlConnection(sconnstring);
}
return _localConn;
}
}
That error occurs when you are not calling SqlConnection.Open(). It has nothing to do with concurrency. Without seeing your actual database access code, I can't help you much more than that. But somewhere along the line, the connection is being created in memory but not connected.
Edit:
In re to a comment, here's the code with using blocks as appropriate. I also took the liberty of parameterizing your query to avoid SQL injection attacks.
public Boolean saveM1ProcessQty(string M1, string M1a)
{
try
{
string sSQL = "INSERT INTO xxx (M1, M1-1) VALUES ('#m1, #m1a')";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["local"].ToString()))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sSQL, conn));
{
cmd.Parameters.AddWithValue("#m1", M1);
cmd.Parameters.AddWithValue("#m1a", M1a);
cmd.ExecuteNonQuery();
}
}
return true;
}
catch(Exception ex)
{
Common.ErrorLog("M1 - " + ex.Message.ToString());
return false;
}
}

Issues with mysql in c#

I have a small problem with connecting c# with a mysql database. When im trying to insert a value from a textbox i get the error below. I was wondering if someone could help me/ explain to me what im doeing wrong.
This is the error that i'm getting:
Unknown column 'test' in 'field list'
This is my code for connecting to the database:
namespace Planner
{
internal class DBConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
private string _database;
private string _uid;
private string _password;
//private string _port;
//private bool succes = false;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
public void Initialize()
{
string connectionString2 = "Server=localhost;Port=3307;Database=test;Uid=root;Pwd=usbw";
//+ "Port:" + _port + ";"
_server = "localhost:3307";
//_port = "3307";
_database = "test";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString2);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
private List<string>[] Select()
{
string selectquery = "SELECT * FROM tabelname";
List<string>[] selectlist = new List<string>[3];
selectlist[0] = new List<string>();
selectlist[1] = new List<string>();
selectlist[2] = new List<string>();
MySqlCommand cmd = new MySqlCommand(selectquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
selectlist[0].Add(dataReader["waarde"] + "");
selectlist[1].Add(dataReader["waarde"] + "");
selectlist[2].Add(dataReader["waarde"] + "");
}
dataReader.Close();
return selectlist;
}
public void Insert(string textvalue)
{
string insertquery = "INSERT INTO testconnectie(text) VALUES ("+textvalue+")";
MySqlCommand cmd = new MySqlCommand(insertquery, _connection);
cmd.ExecuteNonQuery();
}
private void Update()
{
string updatequery = "UPDATE tabelnaam SET waarde='', waarde'' WHERE waarde=''";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatequery;
cmd.Connection = _connection;
cmd.ExecuteNonQuery();
}
private void Delete()
{
string deletequery = "DELETE FROM tabelnaam WHERE waarde=''";
MySqlCommand cmd = new MySqlCommand(deletequery, _connection);
cmd.ExecuteNonQuery();
}
public bool CloseConnection()
{
try
{
_connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "C:\\ChatBackup" + year + "-" + month + "-" + day +
"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "Database Backup";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(#"-u{0} -p{1} -h{2} {3}",
_uid, _password, _server, _database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup! " + ex);
}
}
}
}
Mainform
namespace Planner
{
public partial class MainForm : Form
{
private DBConnect mysql = new DBConnect();
public MainForm()
{
InitializeComponent();
mysql.Initialize();
mysql.OpenConnection();
}
private void _sendMessageButton_Click(object sender, System.EventArgs e)
{
string textvalue = _messageTextBox.Text;
mysql.Insert(textvalue);
}
}
}
Can someone explain to my what im doeing wrong, thanks in advance.
you miss single quote, use like this
string insertquery = "INSERT INTO testconnectie(text) VALUES ('"+textvalue+"')";
use parameters: it is safe and you can avoid most of the exceptions like you currently get
string insertquery = "INSERT INTO YourTableName ([yourColumnName]) VALUES (#ParameterName)";
using (var con = new MySqlConnection(connectionString))
using (var cmd = new MySqlCommand(insertquery, con))
{
cmd.Parameters.AddWithValue("#ParameterName", textvalue);
con.Open();
cmd.ExecuteNonQuery();
}

Issues with the c# datarow

I have a small problem with the c# DataRow Command in my code. Because when im trying to loop trough my mysql database and i have the foreach like this:
foreach (DataRow row in _login._database)
{
//And search for Username and Pass that match
if (row.ItemArray[0].Equals(username) && row.ItemArray[1].Equals(password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
break;
}
//If not, then show this message.
else
{
MessageBox.Show("Username/Password incorrect");
break;
}
}
This error will come up:
Error 1 Cannot convert type 'char' to 'System.Data.DataRow'
Can someone help/explain to me what im doeing wrong.
This is the rest of the code:
namespace Chat
{
public partial class StartupForm : Form
{
private LoginConnect _login = new LoginConnect();
public StartupForm()
{
InitializeComponent();
_login.OpenConnection();
}
private void _loginButton_Click(object sender, EventArgs e)
{
string username = _usernameTextBox.Text;
string password = HashPass(_passwordTextBox.Text);
//Loop through database
foreach (DataRow row in _login._database)
{
//And search for Username and Pass that match
if (row.ItemArray[0].Equals(username) && row.ItemArray[1].Equals(password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
break;
}
//If not, then show this message.
else
{
MessageBox.Show("Username/Password incorrect");
break;
}
}
_login.LoginQuery(username, password);
}
private void button1_Click(object sender, EventArgs e)
{
var register = new RegisterForm();
register.ShowDialog();
}
public string HashPass(string password)
{
MD5 mdvijf = new MD5CryptoServiceProvider();
//compute hash from the bytes of text
mdvijf.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
//get hash result after compute it
byte[] result = mdvijf.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
}
}
LoginCOnnect.cs:
namespace Chat
{
class LoginConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
public string _database;
private string _uid;
private string _password;
//public String MessageRecieved;
private StringList _messagelist = new StringList();
//private string _table = "logingegevens";
private string _port;
//private bool succes = false;
public LoginConnect()
{
Initialize();
}
public void Initialize()
{
_server = "localhost";
_port = "3307";
_database = "testlogin";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
public void LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
int count = 0;
while (dataReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Login Succesfull");
}
else if (count > 1)
{
MessageBox.Show("Acces denied");
}
else
{
MessageBox.Show("Username or passowrd is not correct.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The problem is that in this statement
foreach (DataRow row in _login._database)
you are looping through a string, and so the enumeration of _login._database is an IEnumerable of chars and not of DataRow, so row variable would be a char and not a DataRow.
I suggest you to retrieve the data into an internal DataTable, your LoginConnect code would be like this:
namespace Chat
{
class LoginConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
public string _database;
private string _uid;
private string _password;
private StringList _messagelist = new StringList();
private string _port;
private DataTable _dataTable;
public LoginConnect()
{
Initialize();
}
public DataTable Data
{ get { return _dataTable; } }
public void Initialize()
{
_server = "localhost";
_port = "3307";
_database = "testlogin";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
public void LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
_dataTable = new DataTable();
adp.Fill(_dataTable);
var count = _dataTable.Rows.Count;
}
catch{}//your handling
}
}
}
So you can loop through Data:
foreach (DataRow row in _login.Data.AsEnumerable())
THis line is wrong: (DataRow row in _login._database because _database is type of string. You have to iterate over something that have DataRow like DataTable.
Anyway I would change your code to this:
private void _loginButton_Click(object sender, EventArgs e)
{
string username = _usernameTextBox.Text;
string password = HashPass(_passwordTextBox.Text);
if (_login.LoginQuery(username, password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
}
else
{
MessageBox.Show("Username/Password incorrect");
}
}
and LoginCOnnect.cs method LoginQuery to return bool
public bool LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
int count = 0;
while (dataReader.Read())
{
count = count + 1;
}
if (count == 1)
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}

Categories

Resources