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();
}
}
}
Related
protected override async void OnAppearing()
{
dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "OrderappDb.db");
bool DbExists = File.Exists(dbPath);
var connect = new SqliteConnection("Data Source=" + dbPath);
private bool tableExists(SqliteConnection connection, string tableName)
{
dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "OrderappDb.db");
var connect = new SqliteConnection("Data Source=" + dbPath);
connection = connect;
try
{
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
using (cmd = new SqliteCommand(connection.ToString()))
{
//sqlite_master
cmd.CommandText = $"Select Count(*) from sqlite_master where type='table' and name='{tableName}';";
object result = cmd.ExecuteScalar();
//connection.Open();
int resultCount = Convert.ToInt32(result);
if (resultCount > 0)
return true;
connection.Close();
// sqlite_master
}
return false;
}
catch (Exception ex)
{
return false;
}
}
I am Creating table in sqlite and aceesing that table.
Getting ,ExecuteScalar can only be called when the connection is open.Why I Am Getting above error dont understand. Please help with my snippet.
There is not an overload for SqliteCommand how you are using it. You'll want to use
Using SqliteCommand cmd = new SqliteCommand(yourSqlString, connection) {
Integer val = cmd.executeScalar();
}
https://learn.microsoft.com/en-us/dotnet/api/microsoft.data.sqlite.sqlitecommand?view=msdata-sqlite-7.0.0#constructors
The SqlCommand.ExecuteReader Method Sends the CommandText to the Connection and builds a SqlDataReader. So it need connection.Open(); method to open the connection and this is why the ExecuteScalar method can only be called when the connection open.
Backgournd
I am currently working on a project which will need me to create a local .dbf file which I must then populate with a value. I am currently able to create a .dbf file in a test dir and adding a column to it, however when I later try to add a value to the column, it errors out.
Problem
I am currently not able to write to the column Public in the .dbf file which I created. When the code goes into ExecuteNonQuery();, it an error and is caught in my catch statement.
Working code
public static bool CreateDBF()
{
try
{
string dbfDirectory = #"c:\Users\me\Desktop\New911";
string connectionString = "Provider=VFPOLEDB;Data Source=" + dbfDirectory;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "create table CustomProperties(Public C(60))";
command.ExecuteNonQuery();
connection.Close();
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
}
return true;
}
catch (Exception ex)
{
throw;
}
}
Working Code - appendix:
The above block of code successfully create the .dbf file with the column which I want as the following image will show
Not working code:
public static bool InsertDataIntoDBF(string path)
{
try
{
string strLogConnectionString = "Provider=VFPOLEDB;Data Source=" + path + ";Collating Sequence=machine;Mode=ReadWrite;";
string query = #"INSERT INTO CustomProperties (Public)";
using (OleDbConnection connection = new OleDbConnection(strLogConnectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
new OleDbCommand("set null off", connection).ExecuteNonQuery();
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
catch (Exception ex)
{
throw;
}
}
Updated code blocks
Working block:
public static bool CreateDBF()
{
try
{
string dbfDirectory = #"c:\Users\er4505\Desktop\New911";
string connectionString = "Provider=VFPOLEDB;Data Source=" + dbfDirectory;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "create table CustomProperties(Public C(60))";
command.ExecuteNonQuery();
connection.Close();
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
return true;
}
catch (Exception ex)
{
string viewError = JsonConvert.SerializeObject(ex);
return false; << I have a breakpoint here
}
}
Non-working block:
public static bool InsertDataIntoDBF(string path)
{
try
{
string strLogConnectionString = "Provider=VFPOLEDB;Data Source=" + path + ";Collating Sequence=machine;Mode=ReadWrite;";
string query = #"INSERT INTO CustomProperties (Public) VALUES (#Public)";
using (OleDbConnection connection = new OleDbConnection(strLogConnectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
catch (Exception ex)
{
string viewError = JsonConvert.SerializeObject(ex);
return false; << breakpoint here
}
}
Error caught:
oledbErrors
Message: Syntax error.
NativeError: 0
Source: Microsoft OLE DB Provider for Visual FoxPro
ClassName: System.Data.OleDb.OleDbException
Message: Syntax error.
This works for me. Try it
static void Main(string[] args)
{
try
{
CreateDBF();
Console.WriteLine(ReadDB());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static string dbfDirectory = #"c:\Test\dbTest";
private static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbfDirectory + ";Extended Properties = dBase IV";
public static bool CreateDBF()
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "Create Table CustomProperties ([Public] char(50))";
command.ExecuteNonQuery();
connection.Close();
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
return true;
}
public static bool InsertDataIntoDBF(string path)
{
string query = #"INSERT INTO CustomProperties ([Public]) VALUES (#Public)";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
public static string ReadDB()
{
string res = string.Empty;
string query = #"SELECT * FROM CustomProperties";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("#Public", "True");
connection.Open();
res = (string)command.ExecuteScalar();
connection.Close();
}
return res;
}
The error was purely syntax, and I was guided by a really good example which I found in the following link
https://social.msdn.microsoft.com/Forums/en-US/24eac4c5-3a4d-43f4-8607-ef684919c4af/command-contains-unrecognized-phrasekeyword-vbnet?forum=visualfoxprogeneral
Working Code Blocks
public static bool CreateDBF()
{
try
{
string dbfDirectory = #"c:\Users\er4505\Desktop\New911";
string connectionString = "Provider=VFPOLEDB;Data Source=" + dbfDirectory;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "create table CustomProperties(Public C(60))";
command.ExecuteNonQuery();
connection.Close();
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF");
return true;
}
catch (Exception ex)
{
string viewError = JsonConvert.SerializeObject(ex);
return false;
}
}
public static bool InsertDataIntoDBF(string path)
{
try
{
string strLogConnectionString = "Provider=VFPOLEDB;Data Source=" + path + ";Collating Sequence=machine;Mode=ReadWrite;";
string query = "INSERT INTO CustomProperties(Public) VALUES (?)";
using (OleDbConnection connection = new OleDbConnection(strLogConnectionString))
{
connection.Open();
OleDbCommand cmdInit = new OleDbCommand("set null off", connection);
cmdInit.ExecuteNonQuery();
OleDbCommand command = new OleDbCommand(query, connection);
OleDbParameter publicStatus = command.Parameters.Add("Public", OleDbType.Char);
publicStatus.Value = "True";
command.ExecuteNonQuery();
connection.Close();
}
return true;
}
catch (Exception ex)
{
log4net.LogManager.GetLogger("EmailLogger").Error(JsonConvert.SerializeObject(ex));
string viewError = JsonConvert.SerializeObject(ex);
return false;
}
}
public static bool CreateDBF()
{
...
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
...
}
InsertDataIntoDBF(dbfDirectory + "\\CustomProperties.DBF"); // change 1
return true;
}
catch (Exception)
{
throw; //change2
}
}
public static bool InsertDataIntoDBF(string path)
{
try
{
...
}
catch (Exception)
{
throw; //change 3
}
}
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?
How to stop database query during execution on button click.Is this is possible?I want to end database running query on logout.
SqlCommand.Cancel Method allows you to stop SQL running queries:
If there is nothing to cancel, nothing occurs. However, if there is a command in process, and the attempt to cancel fails, no exception is generated.
Here is code:
class Program
{
private static SqlCommand m_rCommand;
public static SqlCommand Command
{
get { return m_rCommand; }
set { m_rCommand = value; }
}
public static void Thread_Cancel()
{
Command.Cancel();
}
static void Main()
{
string connectionString = GetConnectionString();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Command = connection.CreateCommand();
Command.CommandText = "DROP TABLE TestCancel";
try
{
Command.ExecuteNonQuery();
}
catch { }
Command.CommandText = "CREATE TABLE TestCancel(co1 int, co2 char(10))";
Command.ExecuteNonQuery();
Command.CommandText = "INSERT INTO TestCancel VALUES (1, '1')";
Command.ExecuteNonQuery();
Command.CommandText = "SELECT * FROM TestCancel";
SqlDataReader reader = Command.ExecuteReader();
Thread rThread2 = new Thread(new ThreadStart(Thread_Cancel));
rThread2.Start();
rThread2.Join();
reader.Read();
System.Console.WriteLine(reader.FieldCount);
reader.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
}
}
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;
}
}