I tried connecting a very simple program in C# and save it to database but I always get the exception error which is "System.InvalidOperationException: 'The connection is already open.'"
Here's my code:
namespace sample
{
public partial class Form1 : Form
{
public MySqlConnection connection;
public Form1()
{ InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{ DBConnect dbc = new DBConnect();
dbc.Insert();
}
}
I tried closing the connection when the form start and non to avail.
and for the MySQL class in which I think where the error is:
class DBConnect
{ private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{ Initialize(); }
private void Initialize()
{ server = "localhost";
database = "csample";
uid = "root";
password = "1234";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString); }
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;
} MessageBox.Show("Failed!"); return false; }
}
private bool CloseConnection() {
try
{ connection.Close();
return true; }
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false; }
}
public void Insert()
{
string query = "INSERT INTO info values ('cedie','taguig'); ";
if (this.OpenConnection() == true)
{ MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("CONNECTION OPENED \n SUCCESS!"); }
else if (this.OpenConnection() == false) {
MessageBox.Show("CONNECTION CLOSED \n FAILED!");
}}}}
Don't mind the labels and textboxes as this program is just to execute the mysql
Related
I have a database to manage a school (students and classes).
I have a class with the code to connect to the DataBase and then I call the functions in the main program.
When I try to interact with the DataBase, it warns me that it could not connect to the DataBase or it exceeded the connection time.
I tried to add an ssslmode but it didn't work. I also tried to add a port but it didn't work.
Code for the class:
public class ligacao
{
public MySqlConnection connection;
string server;
public string data_base;
string user_id;
string password;
public void inicializa()
{
server = "localhost";
data_base = "escola";
user_id = "root";
password = "usbw";
string connection_string;
string sslmode = "none";
connection_string = "SERVER=" + server + ";" + "DATABASE=" + data_base + ";" + "UID=" + user_id + "PASSWORD=" + password + ";" + "SslMode=" + sslmode + ";";
connection = new MySqlConnection(connection_string);
}
public bool open_connection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0: MessageBox.Show("Couldn't connect t DataBase."); break; // couldn't connect to database
case 1042: MessageBox.Show("Exceded the connection time"); break; // exceeded the connection time
case 1045: MessageBox.Show("Username/password are incorrect"); break;
}
return false;
}
}
public bool close_connection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
Code for the Main Program:
public partial class consultas : Form
{
ligacao x = new ligacao();
public consultas()
{
InitializeComponent();
x.inicializa();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void consultas_Load(object sender, EventArgs e)
{
//define query
string query = "SELECT designacao FROM disciplinas";
//open connection
if (x.open_connection())
{
//create the comand and associates the query with the connection through the connector
MySqlCommand cmd = new MySqlCommand(query, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["designacao"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
//define query
string queryBI = "SELECT bi FROM alunos";
//open connection
if (x.open_connection())
{
//create the commando and associate the query with the connection through the constructor
MySqlCommand cmd = new MySqlCommand(queryBI, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["bi"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
}
}
I think there is something wrong with your connection string. Try using the MySqlConnectionStringBuilder:
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Host = "localhost";
builder.UserId = "root";
builder.Database = "escola";
builder.Password = "usbw";
connection = new MySqlConnection(builder.ConnectionString);
Try This :
connection_string = #"Data Source = " + server + "; Initial Catalog = " + data_base + "; Integrated Security=True;uid=myUser;password=myPass;";
I'm trying to connect from my c# desktop application to my mysql database. But I'm always receiving the following error:
Cannot connect to any of the specified mysql hosts
Database class:
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 Infinite_Trainer_v2
{
class database_connector
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
// Constructor
public database_connector()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "ip:3306";
database = "dbName";
uid = "username";
password = "password";
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:
MessageBox.Show("Cannot connect to server. Contact administrator.");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
// Select statement
public bool userCheck(string username, string password)
{
string query = "SELECT username, password FROM Users WHERE username = '" + username + "' AND password = '" + password + "'";
bool hasRecords = false;
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows)
{
while (dataReader.Read())
{
hasRecords = true;
}
}
dataReader.Close();
this.CloseConnection();
}
return hasRecords;
}
}
}
Database settings:
Database setting screenshot
Does anyone have a idea what's wrong with my code?
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();
... ...
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.
Im following a C# database connection tutorial however the code they provide for the connection class has a problem, it has an error on dat_set which I'm assuming needs to be set as a variable but I'm unsure. Having looked at the code the tutorial provides many times what i have is exactly the same
The errors are these lines
da_1.Fill(dat_set, "Table_Data_1");
return dat_set;
Here is what i have
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
namespace JBT
{
class DBConnect
{
private string sqlString;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da_1;
public string Sql
{
set { sqlString = value; }
}
public string connection_string
{
set { strCon = value; }
}
public System.Data.DataSet GetConnection
{
get
{ return MyDataSet(); }
}
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sqlString, con);
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
}
}
The Dataset that you want to Fill need to be intialized before
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sqlString, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
Of course this could work only if you have initialized the sqlString and the strCon before calling this code. This should be assumed because you say that the error occurs at the Fill line
The
System.Data.DataSet MyDataSet() is not what you have to put in your code if you are using Mysql
first initialize the code.
then write methods to open and close connection.
now you are ready for the db connection.
public class DbConnection
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
private void initialize()
{
server = "localhost";
database = "yourdatabase";
uid = "root";
password = "";
string connectionString = "server=" + server + ";database=" + database + ";uid=" + uid + ";password=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open 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;
}
return false;
}
}
if you want to develop complete db connection use this site: http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
helped me a lot :)