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?
Related
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.
This Code is establishing a Mysql Connection.
namespace TrialConnection
{
public class DataConnection
{
public static string database = "";
public static string databasename = "";
public static string user = "";
public static string password = "";
public static string charset = "latin1";
string connString = "";
public DataLayer(ref MySqlCommand newconnection)
{
connString = "On server = " + database + "; Databasename = " + databasename + "; User = "
+ user + "; Pass = " + password + "; Locale = " + charset;
newconnection = new MySqlCommand();
}
public bool modifyData(ref MySqlCommand newconnection, Alter_Procedures myQuery)
{
MySqlConnection myconnection = new MySqlConnection(connString);
newconnection.Connection = myconnection;
newconnection.CommandText = modifyQuery.ToString();
newconnection.CommandType = CommandType.StoredProcedure;
MySqlTransaction mytransaction = null;
try
{
myconnection.Open();
mytransaction = myconnection.BeginTransaction();
newconnection.Transaction = mytransaction;
newconnection.ExecuteNonQuery();
mytransaction.Commit();
mytransaction.Dispose();
myconnection.Close();
myconnection.Dispose();
}catch(Exception e){}
}
public bool getData(ref MySqlCommand newconnection, Retrieve_Procedures allproc, ref MySqlDataReader myReader)
{
MySqlConnection myConnection = new MySqlConnection(connString);
newconnection.Connection = myConnection;
newconnection.CommandType = CommandType.StoredProcedure;
newconnection.CommandText = allproc.ToString();
myConnection.Open();
myReader = newconnection.ExecuteReader();
}
}
}
Whenever I try to connect and there is no stored procedure yet in the database, it is not always taking the values for my database, databasename, user, Password and charset.
I tried to debug it and found something, however I am not sure whether I found everything.
I am very thankful for help.
I created a DLL file in c# with the following content:
namespace GenerateMemo
{
class GenerateMemo
{
public MySqlConnection connection;
private string server;
private string port;
private string database;
private string uid;
private string password;
public void SqlConnect(string _server, string _port, string _database, string _uid, string _password)
{
string connectionString;
connectionString = "SERVER=" + _server + ";" + " PORT=" + _port + ";" + "DATABASE=" +
_database + ";" + "UID=" + _uid + ";" + "PASSWORD=" + _password + ";";
connection = new MySqlConnection(connectionString);
connection.Open();
}
public void sqlNonQueryN(string query)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
}
and I dont know how to call those methods inside the file. I am using Visual Studio and already imported it as reference. Please tell me how to use my DLL file. I need to use those methods in another project. Thanks a lot. :)
First, you need to make your GenerateMemo class public to use it in another assembly. Right now it is internal (default access modifier of class).
Then, if you already added this dll as reference to your project - basically you need to create instance of your class and call it methods.
var memo = new GenerateMemo();
memo.SqlConnect(....)
and so on.
And make sure you've included using GenerateMemo; namespace in the file where you planning to use it.
A lot more readable:
public class GenerateMemo
{
private MySqlConnection connection;
private string server, database, uid, password;
private uint port;
public GenerateMemo(string _server, uint _port, string _database, string _uid, string _password) //constructor
{
server = _server;
port = _port;
uid = _uid;
password = _password;
}
private void BuildConnection()
{
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Server = server;
builder.Port = port;
builder.Database = database;
builder.UserID = uid;
builder.Password = password;
connection = new MySqlConnection(builder.ConnectionString);
}
public void sqlNonQueryN(string query)
{
if (connection == null)
{
BuildConnection();
}
connection.Open();
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
}
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;
}
}
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;
}