I developed a POS like application and during testing with 2 PCs I didn't encounter any problems with the speed. It's just a simple LAN cable setup between 2 computers. But when I deployed it in a client, it ran slow.
The client has 1 PC serving as the admin and the main server, and there are 2 more PCs serving as the cashier. All connected in a router. The cashiers are connected to the admin's PC (main server) to retrieve, insert, update and delete data. I just want to ask if there are processes that needs to be done in MySQL or are there anything wrong with my codes when connecting to the database.
Here's my sample code for connecting to the database, I doubt having problems with it as this has been the standard in connecting to a database and adding records. Just in case I might bore you with codes, you can simply jump to the second code I posted, I have a comment there asking if the initialization of my class is correct. Thanks everyone!
class DBConnection
{
private MySqlConnection connection;
private MySqlCommand cmd;
private MySqlDataReader dr;
private DataTable tbl;
private MySqlDataAdapter da;
private DataSet ds;
private string connectionString;
private string server;
private string database;
private string uid;
private string password;
private frmNotifOk myNotification;
public DBConnection()
{
Initialize();
}
private void Initialize()
{
server = "CASHIER";
database = "sampledb";
uid = "root";
password = "samplepassword";
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.");
break;
}
return false;
}
}
private void CloseConnection()
{
try
{
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
public void AddRecord(String DBQuery, bool showNotif)
{
string query = DBQuery;
bool notify = showNotif;
try
{
if (this.OpenConnection() == true)
{
cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
if (notify)
{
MessageBox.Show("Item successfully added.");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
this.CloseConnection();
}
}
And finally, here's how I use the method in a form:
public partial class frmNewCashier : Form
{
private DBConnection dbConnect;
string sampleDataSource= "SELECT * FROM SampleTable";
public frmNewCashier()
{
InitializeComponent();
//Is this the correct place of initializing my DBConnection class?
dbConnect = new DBConnection();
}
private void frmCashier_Load(object sender, EventArgs e)
{
try
{
dgvSearchItems.DataSource = dbConnect.DatabaseToDatagrid(dgvSearchItemsDataSource);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
I put the initialization of DBConnection class in public frmNewCashier(), is this the correct place or should I put it in Load event or somewhere? I'm thinking if this has bearing to the slowness of database. Aside from this question, do you know anything that I might have missed that causes the slowness?
class DBConnect
{
public MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
public void Initialize()
{
server = "localhost";
database = "db_sea_horses";
uid = "root";
password = " " ;
//password = "123";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
public bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{ //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;
}
return false;
}
}
//Close connection
public bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
class DBmethods : DBConnect
{
DataSet dataset2;
public void input_sql(string query)
{
try
{
//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
int x = cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
catch(MySqlException myex)
{
MessageBox.Show(ex.Message);
}
}
///////////////////////////////////////////////
///// select
/////////////////////////////////////////////
public DataSet output_sql(string query,String table_name)
{
//Open connection
this.OpenConnection();
DataSet dataset = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, connection);
adapter.Fill(dataset, table_name);
//close Connection
this.CloseConnection();
//return list to be displayed
return dataset;
}
}
}
method calling example
1) insert / update / delete statement
DBmethods dbm = new DBmethods();
dbm.input_sql(" you can excute insert / update / delete query");
2) select statement
DataSet ds = dbm.output_sql("select * from storage_bunkers where job_id LIKE '%" + itemname.Text + "%' ", "storage_bunkers");
DataView myView = ((DataTable)ds.Tables["storage_bunkers"]).DefaultView;
dataGridView1.DataSource = myView;
First, try pinging from client machine to server which has installed SQL server. If it is taking too much time then there's problem with network connection.
If not, put a debug point and try debugging then identify the location that taking too long. Then you will able to get a answer.
Also, do not forget to close each and every db connection after using that.
Related
As said in the title, I tried to write some prepared statement on Visual Studio 2017.
But when Starting my program, I have an exception, called
System.InvalidOperationException :'The connection property has not
been set.'
Here's the associated code :
namespace Sequence
{
class Database
{
private MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlConnection conn; //new connection
public void Connect()
{
string myConnectionString; //connection String
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=internship;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
public void Disconnect()
{
try
{
conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
public void AddData()
{
cmd = new MySql.Data.MySqlClient.MySqlCommand();
//Connecting to database
Connect();
try
{
//Prepare a statement
cmd.CommandText = "INSERT INTO storing VALUES(#longitude, #latitude, #status, #path)";
cmd.Prepare();
//Adding values
cmd.Parameters.AddWithValue("#longitude", 0.5);
cmd.Parameters.AddWithValue("#latitude", 0.5);
cmd.Parameters.AddWithValue("#status", "false");
cmd.Parameters.AddWithValue("#path", "C:\\temp\\sequence");
//Executes the Query
cmd.ExecuteNonQuery();
//Writes in Console
Console.WriteLine("Line added successfully");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occured: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
This is my class that connects to the database.
I have a main program where I just wrote this :
static class Program
{
[STAThread]
static void Main()
{
Database db = new Database();
db.Connect();
db.AddData();
db.Disconnect();
}
}
Any idea of why I get this exception ?
I followed the tutorial on this link :
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html
Thanks in advance
You didn't set the connection property of your command:
cmd.Connection = conn;
Although it's recommended to use the using-statement that Provides a convenient syntax that ensures the correct use of IDisposable objects like SqlConnection. It will also close the connection
I create a program to backup the whole DB from SQL server 2014 , i used the code before it was work perfectly on another laptop (was working on it coding with c#).
now i'm trying to backup not work at all this is the code:
1/- SqlConnection:
SqlConnection con = new SqlConnection(WindowsFormsApplication11.Properties.Settings.Default.database1ConnectionString);
2/- textbtn1
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.SelectedPath;
BackupButton.Enabled = true;
}
}
3/- textbtn2 code :
private void BackupButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
try
{
if(textBox1.Text==string.Empty)
{
MessageBox.Show("please enter backup file location");
}
else
{
string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + textBox1.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using(SqlCommand command = new SqlCommand(cmd,con))
{
if(con.State!=ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("database backup done successefully");
BackupButton.Enabled = false;
}
}
}
catch
{
}
}
** even this code not work and no message show up :p , don't know why ?
i changed every thing , i created a new class called DBconnect :
class DBconnect
{
public SqlConnection myConn = new SqlConnection(#"Data Source=MYSERVERNAME;Initial Catalog=MYDBNAME;User ID=sa;Password=12345");
public void backup(string name_path)
{
try
{
string query = "Backup Database MYDBNAMEto Disk ='" + name_path + ".bak'";
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = query;
myCommand.Connection = myConn;
myCommand.ExecuteNonQuery();
MessageBox.Show("sauvegarde succès", "sauvegarde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
}
in my form i did this :
DBconnect conn = new DBconnect();
in backup textbtn2 i did this :
string Namefile = textboxBATH.Text + "\\MYDBNAME" + " " + DateTime.Now.ToShortDateString().Replace('/', '-') + "-" + DateTime.Now.ToLongTimeString().Replace(':', '-');
Conn.backup(Namefile);
in this case i faces this erorr message :
Cannot open backup device. Operating system error 5(Access is denied.) BACKUP DATABASE is terminating abnormally.
i thought SQL service might not have permission to the Path where backup bath is supposed to be created . and i create new folder in my Desktop and gave it the permission Read+Write .. and this not work too .. :p
thank you all .
I decided to create an application that connects to an MySQL server but it seems that there is a problem with my code.
public partial class FRM_LOGIN : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public FRM_LOGIN()
{
InitializeComponent();
}
private void BTN_CONNECT_Click(object sender, EventArgs e)
{
server = "localhost";
database = "databasenamehere";
uid = "root";
password = "root";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";old guids=true;";
connection = new MySqlConnection(connectionString);
try
{
if (TXTBOX_USERNAME.Text == "" || TXTBOX_PASSWORD.Text == "")
{
MessageBox.Show("Please fill up all the fields of the login form.");
}
else
try
{
connection.Open();
MySqlCommand com = new MySqlCommand("SELECT * FROM tbl_login WHERE (user_id=#id AND user_password=#pwd)", connection);
com.Parameters.Add(new MySqlParameter("id", SqlDbType.NVarChar)).Value = this.TXTBOX_USERNAME.Text;
com.Parameters.Add(new MySqlParameter("pwd", SqlDbType.NVarChar)).Value = this.TXTBOX_PASSWORD.Text;
MySqlDataReader myReader = com.ExecuteReader();
myReader.Read();
if (myReader.HasRows == true)
{
MessageBox.Show("Login Successfull", "Login Information");
this.Hide();
FRM_MAIN frm_main = new FRM_MAIN();
frm_main.Show();
}
else
{
MessageBox.Show("Invalid User Name or Password", "Hello", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
connection.Close();
}
catch (MySqlException ex)
{
throw;
}
}
catch (MySqlException ex)
{
{
case 0:
MessageBox.Show(ex.Message);
MessageBox.Show("Cannot connect to server. Contact administrator", " Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case 1045:
MessageBox.Show(ex.Message);
MessageBox.Show("Invalid username/password, please try again");
break;
}
}
}
}
ALOT of it is patch work from various answers from here and some tutorials, so please don't judge, complete newbie here.
So as most of you can tell, i have a form with 2 textboxes and a button. My goal was to authenticate the user by using finding out if the credentials are in the table tbl_login. If there are results, close form1 open another form.
My problem at the moment is that every time I click the button an exception is thrown.
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll
{"Input string was not in a correct format."}
and it points me out to the
MySqlDataReader myReader = com.ExecuteReader();
Any ideas why this keeps on happening? Any help would be greatly appreciated.
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?
I'm getting an This Table already exists error from Visual Studio 2012. I checked it in MySqlWorkbench and the Xampp Directory, but I didn't find anything. I've even tried it with DROP TABLE IF EXISTS tablename; but this doesn't work either.
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 = "localhost";
database = "";
uid = "root";
password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
connection.Dispose();
CreateDatabase(" DROP DATABASE IF EXISTS boerswatch; CREATE DATABASE boerswatch;");
server = "localhost";
database = "boerswatch";
uid = "root";
password = "";
string connectionString1;
connectionString1 = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString1);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException e)
{
switch (e.Number)
{
case 0:
MessageBox.Show("Keine Verbindung zum Server Möglich!");
break;
case 1045:
MessageBox.Show("Ungültiger Benutzername oder Passwort!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException e)
{
MessageBox.Show(e.Message);
return false;
}
}
public void CreateDatabase(String query)
{
if (OpenConnection())
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
CloseConnection();
}
catch (MySqlException e)
{
MessageBox.Show(e.Message);
}
}
}
public void CreateTable(String query)
{
if (OpenConnection())
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
CloseConnection();
}
catch (MySqlException e)
{
MessageBox.Show(e.Message);
}
}
}
public void Insert(String query)
{
if (this.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
}
public partial class Form1 : Form
{
static XmlSerializer serializer;
static FileStream stream;
public List<Bank> banks;
public List<Object> pers;
public DBConnect data;
public Form1()
{
InitializeComponent();
checkFiles();
}
private void checkFiles()
{
String user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
banks = new List<Bank>(5);
if (!Directory.Exists(#"C:\xampp\mysql\data\boerswatch") )
{
data = new DBConnect();
createBanks();
}
else
{
//loadBanks();
//loadAccounts(pers);
}
}
public void createBanks()
{
Bank b1 = new Bank("Raiffeisen");
Bank b2 = new Bank("Erste Bank");
Bank b3 = new Bank("BAWAG");
banks.Add(b1);
banks.Add(b2);
banks.Add(b3);
data.CreateTable("DROP TABLE IF EXISTS Banken; CREATE TABLE Banken( name VARCHAR(20) PRIMARY KEY);");
data.Insert("INSERT INTO Banken VALUES(" + b1.Name + ");");
data.Insert("INSERT INTO Banken VALUES(" + b2.Name + ");");
data.Insert("INSERT INTO Banken VALUES(" + b3.Name + ");");
listBox1.DataSource = banks;
}
}