unable to connect to any of the specified MySQL hosts - c#

I am trying to create a login form connected to a MySQL database. I installed the sql connector inserted in the form but when I try to connect I get error unable to connect to any of the specified MySQL hosts. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ECBSRecruitmentAgencySoftware
{
public partial class LogIn : Form
{
public LogIn()
{
InitializeComponent();
}
public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=think-tek.net;user=ctutorial;password=chang3d;database=ctutorial_logintest;");
MySqlCommand cmd = new MySqlCommand("Select * FROM login WHERE user_name = `" + username + "` AND user_pass = `" + password + "`;");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(textBox1.Text, textBox2.Text) == true)
{
MainScreen F2 = new MainScreen();
F2.Show();
this.Hide();
}
else MessageBox.Show("Wrong details!");
}
}
}

This site is pretty helpful in terms of connection strings. Your connection string seems to be invalid.
Also: Make sure your user has the proper access privileges. Many hosting providers only enable access from localhost. You may have to request that they enable your user for remote access.

My connection string for MySQL is:
string mySqlConn = "server=localhost;user=username;database=databasename;port=3306;password=password;";
What exception is thrown for your connection string? There should be a error number.

Try the connection string in given format in the sample:
public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("SERVER=localhost;" +
"DATABASE=mydatabase;" +
"UID=testuser;" +
"PASSWORD=testpassword;");
MySqlCommand cmd = new MySqlCommand("Select * FROM login WHERE user_name = `" + username + "` AND user_pass = `" + password + "`;");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}

I had the same problem and error was in connection string! Somehow, I declare it twice to two different locations. Once to my localhost and second time to server machine database. When I published the project on client machine it was impossible to connect to localhost(what was my computer).:-) and I was wondering how do I get this: "unable to connect to any of specified mysql hosts"
this is how man can make his life complicated for days!:-)
of course, i was able to connect to db on server machine.
So, just for example, this was my problem. And, solution was to declare to it once and to one database!!!
And also, I would like to share my connection string that worked just fine:
cs = #"server=xxx.xxx.xxx.xxx;uid=xxxx;password=xxxxxxxxx;database=xxxxx;port=3306";

your string connection is right there is no error,but fist check it on local server
this is exception only raise your xampp is not running, first start xampp
go to browser and type localhost,if its working you will see xampp menu
if it open localhost then try to connect whatever your server is
string connection = "server=localhost;database=student_record_database;user=root;password=;";
MySqlConnection con = new MySqlConnection(connection);

public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("SERVER=xx.xx.xx.xx;DATABASE=dbname;UID=user;PASSWORD=password;CheckParameters=False;");
MySqlCommand cmd = new MySqlCommand("Select * FROM login WHERE user_name = `" + username + "` AND user_pass = `" + password + "`;");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}

Related

Inserting data into Oracle database using c#

I get this error "ora-00928 missing select keyword" when using a button to submit the query. I have other queries on other buttons and the select statements work but for some reason the insert statement doesnt work.
I've seen other posts on this error but nothing seems to help mine
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 System.Data.OleDb;
namespace Oracle
{
public partial class Register : Form
{
string name;
int pass;
int repass;
string email;
public Register()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=DESKTOP-HQCK6F1:1521/CTECH;Persist Security Info=True;User ID=system;Password=G4ming404;Unicode=True");
OleDbCommand cmd = new OleDbCommand();
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
cmd.Connection = con;
cmd.CommandText = "INSERT INTO SYSTEM.CUSTOMER('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')" + "VALUES('%"+ null + "%','%'" + txtname.Text + "%','%'" + txtemail.Text + "%','%'" + txtpass.Text + "%')";
con.Open();
if (pass == repass)
{
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else {
MessageBox.Show("Success!");
}
MessageBox.Show("User has been created");
this.Close();
Form1 login = new Form1();
login.Show();
}
else {
MessageBox.Show("Password mismatch");
}
con.Dispose();
}
There are some problems in your query.
First you don't need single quotes around the column names, You need double quotes only if any of your columns has the same name as a reserved keyword.
Second problem is the string concatenation of the input boxes text to the query command. This should be avoided at all cost because it is the source of parsing problems and sql injection hacks. Use parameters instead.
Finally your OleDbConnection should be local to your method and inside a using statement to ensure correct disposing of the unmanaged resources also in case of exceptions
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
if (pass != repass)
{
MessageBox.Show("Password mismatch");
return;
}
string cmdText = #"INSERT INTO SYSTEM.CUSTOMER
(CUSTOMER_NAME, CUSTOMER_EMAIL, CUSTOMER_PASSWORD)
VALUES(?,?,?)";
using(OleDbConnection con = new OleDbConnection(.......))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("p1", OleDbType.VarChar).Value = txtname.Text;
cmd.Parameters.Add("p2", OleDbType.VarChar).Value = txtemail.Text;
cmd.Parameters.Add("p3", OleDbType.VarChar).Value = txtpass.Text ;
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else
{
MessageBox.Show("Success!");
MessageBox.Show("User has been created");
}
}
Form1 login = new Form1();
login.Show();
}
I have also removed the passing of a parameter for the CUSTOMER_ID field. This seems to be a field that is calculated automatically by Oracle (a Sequence?) and thus you don't need to provide a value for it.
Finally an advice. Do not store password in plain text in the database. This is a security risk very seriours. You should read Best way to store passwords in a database
Your CommandText seems wrong. Why do you wrap all values with '%'? And you should pass null as string. Concatination with null does not changes any string value.
I think it should be:
cmd.CommandText = $#"INSERT INTO SYSTEM.CUSTOMER
('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')
VALUES(NULL, {txtname.Text}, {txtemail.Text}, {txtpass.Text})";

Check credentials of SQL Login

I can create an SQL login account for an user as follows:
CREATE LOGIN [myusername] WITH PASSWORD = N'mypassword', CHECK_POLICY= OFF;
I can check e.g. if 'myusername' exists:
SELECT * FROM sys.server_principals WHERE name = N'myusername'
But how can I check if 'myusername' and a password 'wrong_password' supplied by the user are correct?
My solution in C# is with the help of Roger as follows:
private static bool SqlLoginExists(string username)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=.;" + "Integrated Security=SSPI;";
connection.Open();
string sql_command = "SELECT count(*) FROM sys.server_principals WHERE name = N'" + username + "'";
using (SqlCommand command = new SqlCommand(sql_command, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (reader.GetValue(0).ToString() == "1")
{
return true;
}
}
}
}
return false;
}
public static bool CheckSQLCredentialsIfLoginExists(string username, string password)
{
bool SqlUserExists = SqlLoginExists(username);
if (SqlUserExists)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=.;" + "User id=" + username+";Password=" + password +";";
try
{
connection.Open();
return true;
}
catch (SqlException ex)
{
connection.Dispose();
return false;
}
}
else
{
return true; // it is not a problem for me if account does not exist (as it will be created later), I am only worried about the case when the credentials are wrong
}
}
You can use the pwdcompare() function:
select pwdcompare(N'MyWrongPassword', sl.password_hash) as [Match]
from master.sys.sql_logins sl
where sl.name = N'MyLogin';
However, there is a very big chance you are working in a wrong direction - it is more correct to try and establish connection using supplied credentials.

c# - How can i check user(created or not created)

I'm working on MySql 5.6.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using MySql.Data.MySqlClient;
namespace MySqlRank
{
class Sql
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public Sql()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "db";
uid = "root";
password = "pass";
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)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//Insert statement
public void Successful(ulong Id)
{
//if(NotCreated)
{
string query = "INSERT INTO rank(id, trades) VALUES('" + Id + "', '1')";
//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();
}
}
//else if (created)
{
string query = "UPDATE rank SET trades='1' WHERE id='" + Id + "'";
//Open connection
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
}
//Delete statement
public void Delete(ulong Id)
{
string query = "DELETE FROM rank WHERE id='"+ Id +"'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM rank";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = 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
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["trades"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
}
}
My question on successful void.I try try-cath method but this isn't work.(Id is Unique Key).Afaik i'm need select method but i can't.My table name is rank(id, trade).I'm need if created update trades +1.if not created,create a new user.I'm only need check created or not created.
If I understand your question correct you want to check if the row already exist in your table? If so you can in your catch statement check for primary key violation:
catch(MySqlException ex)
{
this.CloseConnection();
if(ex.Number == 1067)
{
//Handle exception
}
}
EDIT: After testing your code on my own machine I found out that there is nothing wrong with this.OpenConnection(). And my code ran successfully. Are you sure that the credentials given to the connectionString are valid?

using IF condition inside a while loop in C#

I have a problem with my C# code. I have created a login form in C# 2010. When I am validating the user name, I used an if-condition inside the while loop but the thing is that even when the username and password are correct, it executes the else-statement. Please help me to solve this.
Here is my code :
private void btnlogin_Click(object sender, EventArgs e) {
string connection=
#"Data Source=.\SQLEXPRESS;"
+" AttachDbFilename=|DataDirectory|ResturantDB.mdf;"
+" Integrated Security=True; User Instance=True";
SqlConnection cn=new SqlConnection(connection);
try {
cn.Open();
}
catch(Exception) {
// print the exception's message?
MessageBox.Show("Connection to Database failed; check Connection!");
}
SqlCommand cmd=new SqlCommand("SELECT * FROM [Login]", cn);
cmd.Connection=cn;
SqlDataReader reader=null;
reader=cmd.ExecuteReader();
while(reader.Read()) {
if(
txtuser.Text==(reader["Username"].ToString())
&&
txtpass.Text==(reader["Password"].ToString())
) {
//MessageBox.Show( "logged in!" );
Home newhome=new Home();
newhome.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect credentials!");
}
}
}
you should use a break, when a username is found in your if condition like
bool found = false;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) && txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
found = true;
break;
}
}
if (!found)
MessageBox.Show("Incorrect credentian..!");
you get into the else block because if any login is not correct, the messagebox appears and that is in n-1 cases in your code.
You're checking if all users have the same user name and password. You need to refine your SQL to select only that one user. Also, please read into password hashing for the sake of your users.
Because its in a loop.
create a bool variable. update its value in loop (if found same username and password) and check outside based on its value.
Do this
bool found;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) &&
txtpass.Text == (reader["Password"].ToString()))
{
found = true;
break;
}
}
if (found)
{
MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show("Incorrect credentian..!");
}
I will solve it on this way:
private void btnlogin_Click(object sender, EventArgs e)
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ResturantDB.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
}
catch (Exception)
{
MessageBox.Show("Conncetion to Database faild check Connection !");
}
while (true)
{
SqlCommand cmd = new SqlCommand("SELECT [Password] FROM [Login] WHERE [Username] = '" + txtuser.Text + "'", cn);
cmd.Connection = cn;
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
if (!reader.HasRows)
MessageBox.Show("User does not exist. Please, try again.");
else
{
//username should be unique, so only one row is possible to have
reader.Read();
if (txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
return;
}
else
MessageBox.Show("Incorrect credentian..! Try again.");
}
}
}
Simplest and Secure method
SqlCommand cmd = new SqlCommand("Select uname, pswd from [Login] where uname =#uname and pswd =#ps", conn);
cmd.Parameters.Add(new SqlParameter("#uname", "username here"));
cmd.Parameters.Add(new SqlParameter("#ps", "pasword here"));
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//MessageBox.Show( "logged in!" );
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show( "Incorrect credentials!" );
}
No need to loop thru the records for your case
use this query, compate username and password in the query:
"SELECT * FROM [Login] where Username='" + txtuser.Text "' and password = '" + txtpass.Text + "'"

Connection leak in database class

I have a simple C# MySQL connection class as:
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Diagnostics;
using System.IO;
using MySql.Data.MySqlClient;
namespace FSB
{
public class DBConnect
{
private MySqlConnection connection;
private string server;
public string port;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
~DBConnect()
{
//close connection
this.CloseConnection();
}
//Initialize values
private void Initialize()
{
// Local Database
server = "localhost";
database = "mydatabase";
uid = "user";
password = "pass";
string connectionString;
connectionString = "SERVER=" + server + ";Port=" + port + ";" + "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:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
public bool CloseConnection()
{
try
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
connection.Dispose();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
return true;
}
//Insert statement
public void Insert(String query)
{
//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(string query)
{
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Delete statement
public void Delete(string query)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
public MySqlDataReader getRecord(string query)
{
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader;
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
reader = cmd.ExecuteReader();
return reader;
}
return null;
}
//Check Duplicate statement return true if not found
public bool checkDuplicate(string tableName ,String fieldName,String checkValue)
{
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader;
int rowCount = 0;
//Assign the query using CommandText
String query = "Select * from `" + tableName + "` Where `"+fieldName + "` = '"+ checkValue +"'";
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
reader = cmd.ExecuteReader();
while (reader.Read())
{
//get rows
rowCount++;
}
//close connection
this.CloseConnection();
if (rowCount > 0)
{
return false;
}
}
return true;
}
}
}
Can anyone please where I am losing the connection as the connection remains open even after the object is out of scope every time the i use to do any operation a new connection is created and a previous connection is not closed. so I am running out of the connection limit to mysql ?
I suggest you to use using blok in order to clean your non managed object, your connection in this sample
using (var connection = new MySqlConnection("..."))
{
....
}
Nota : using blok execute dispose in the end of treatment in roder to clean
public void Insert(String query)
{
using(var connection = new MySqlConnection("..."))
{
connection.Open();
using(var cmd = new MySqlCommand(query, connection))
{
cmd.ExecuteNonQuery();
}
}
}

Categories