Verify if mysql command executed - c#

I am using
public static bool command(string input, MySqlConnection con)
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
With as an example:
bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val2')", connection);
if (!comm) textBox1.Text += "Command failed";
else textBox1.Text += "Command successful";
Which correctly adds Command successful to textbox1.
But when I change sometable to sometablee, textbox1 stays empty. I was expecting it to notify me the command failed (sometablee does not exist), but it didn't.
Can anyone tell me why?
Full code:
mysql_command:
class mysql_command
{
public static bool command(string input, MySqlConnection con)
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
}
mysql_connect:
class mysql_connect
{
private MySqlConnection connection = null;
public MySqlConnection connect(string server, string database, string UID, string password)
{
try
{
string MyConString = "SERVER=" + server + ";" +
"DATABASE=" + database + ";" +
"UID=" + UID + ";" +
"PASSWORD=" + password + ";";
connection = new MySqlConnection(MyConString);
connection.Open();
}
catch (Exception ex) { Console.WriteLine("MySQL connect error : "+ex.Message); }
return connection;
}
public void disconnect()
{
connection.Close();
}
}
Usage:
private void Form1_Load(object sender, EventArgs e)
{
mysql_connect con = new mysql_connect();
MySqlConnection connection = con.connect("server1.x.x", "somedb", "user", "pass");
bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val1')", connection);
if (!comm) textBox1.Text += "Command failed";
else textBox1.Text += "Command successful";
}

The reason is as I expected, you will get an exception in your command method,
public static bool command(string input, MySqlConnection con)
because requested table is not exists, ....
Edit your command method to handle exception:
public static bool command(string input, MySqlConnection con)
{
try
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
catch
{}
return false;
}

Related

C# SQL Connection string " can't find the table "

Currently I'm working on a project that generates files....().
Everything seems to work well. I can connect to the database and my methods of reading and writing are working, too, but I can't find the table. I have an error:
$exception {"Invalid object name 'T_SAL'."} System.Data.SqlClient.SqlException
I don't know if the problem is with my connection string or something else!
Is there anyone that can help me with this, please?
My methods' code:
//SQL connection Methods**
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
{
try
{
SqlConnection conn = new SqlConnection();
String Securité;
if (Authentification)
{
Securité = "Integrated Security = true";
}
else
{Securité = "User Id =" + SQL_LOGIN + ";" + "Password =" + SQL_PASSWORD;}
conn.ConnectionString = "Data Source=" + SQL_SERVER + ";Initial Catalog=" + BASE_CONSOLE + ";" + Securité + ";";
conn.Open();
return conn;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return null;
}
// Generation :
private void Gen_f_Click(object sender, EventArgs e)
{
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
if (conn == null)
{
MessageBox.Show("Connexion impossible");
return;
}
try
{
//traitement du fichier des salaeiés
var lines = Methodes.lecture(fp_text.Text);
foreach (var ligne in lines)
{
string[] cols = ligne.Split(char.Parse(";"));
string Matricule = cols[0];
if (Matricule != "" && MatriculeExiste(conn, Matricule) == false)
{
string ligneSorties = "";
ligneSorties = ligneSorties + cols[0] + ";";
Methodes.Ecriture(ligneSorties, "fp_sorties.'Text'", true);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private bool MatriculeExiste(SqlConnection conn, string Matricule)
{
SqlCommand command = new SqlCommand("SELECT MatriculeSalarie FROM [T_SAL] WHERE MatriculeSalarie='" + Matricule + "'", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return true;
}
else
{
return false;
}
}
}
The issue seems to be in the order of parameters that you pass to OpenSql method:
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
This is how you call it:
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
There is definitely some mismatch with the order of parameters, your declaration expects SQL_Login, SQL_PASSWORD, SQL_SERVER, BASE_CONSOLE and you are passing SQL_SERVER, BASE_CONSOLE, SQL_LOGIN, SQL_PASSWORD
So if you use Windows Authentication, it would work, because you are not passing login and password, but instead of correct Database Name you are passing password, so your user ends up into Master db, which does not contain required table.

Get value from database and put it into textbox

I totally new at programming and i am learning about, classes, methods connection with mysql.
So i have a class called take and i have a method to get last value from my database table.
namespace Budget
{
class take
{
private MySqlConnection connection;
private string datasource;
private string port;
private string username;
private string password;
public take()
{
Initialize();
}
private void Initialize()
{
datasource = "localhost";
port = "3306";
username = "root";
password = "root";
string connectionString;
connectionString = "DATASOURCE=" + datasource + ";" + "PORT=" + port + ";" + "USERNAME=" + username + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
private bool OpenConnection()
{
connection.Open();
return true;
}
private bool CloseConnection()
{
connection.Close();
return true;
}
public decimal budget()
{
string query =
#"SELECT balance
FROM history
ORDER BY id DESC
LIMIT 1 ";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
return Convert.ToDecimal(reader.GetValue(0));
else
return 0m;
}
}
else
return 0m;
}
}
}
I want to put that value in my main Form TextBox. But when i write in main main Form
take.balance();
Warning Warning 1 Field Budget.Form1.take is never assigned to, and will always have its default value null
So the question is, how i can put that value from database to my main Form textbox?

C# - Why is MySQL Server slow in my server machine?

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.

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?

"Table already exists" but it doesn't

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;
}
}

Categories