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?
if (txtUsername.Text != "")
{
string q = "insert into info(Username) values ('" + txtUsername.Text.ToString() + "')";
dosomething(q);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
if (txtPassword.Text != "")
{
string a = "insert into info(Password) values ('" + txtPassword.Text.ToString() + "')";
dosomething(a);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Every time I run this it always show that error. I dont know how to fix it.
The code should record the data i put in a textbox to ms access database. plz helpp
Presumably, you've initialized cn somewhere by doing something like
cn = new SqlConnection();
You need to pass the connection string for the database to the constructor:
cn = new SqlConnection("your connection string here");
or set it sometime later, before you connect:
cn.ConnectionString = "your connection string here";
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 have a log viewing application that writes log statements to a database and then sends them from the database to the log viewer GUI. I want to be able to open more than one instance of the log viewer but when I do it will be creating a database with the same name as the previous instance of the viewer. I've tried creating a database with a different name if one has already been created but that doesn't seem to work. Any suggestions? Here's the code for creating/accessing/destroying databases:
public class Database
{
public bool hasAdminPriv
{
get;
set;
}
public bool hasBeenCreated
{
get;
set;
}
public Database()
{
hasAdminPriv = true;
//Construction checks to see if user has Admin priveleges
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!isElevated)
hasAdminPriv = false;
}
//returns true if the database creation was successful
public bool CreateDatabase()//creates a database dynamically by making a query request to the server
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
int done = 0;
while (done < 10)
{
String str2 = "CREATE DATABASE" + done + " MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand2 = new SqlCommand(str2, myConn);
try{
myCommand2.ExecuteNonQuery();
}
catch{
++done;
}
myConn.Close();
hasBeenCreated = true;
return true;
}
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
hasBeenCreated = true;
return true;
}
//Creates the table in the database by a query request
//a return value of true means Database was created succesfully
public bool CreateTable()
{
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=MyDatabase;Integrated Security=True");
string createString = "CREATE TABLE storage (ID INT NOT NULL, Level varchar(255) , LevelInt INT, DateTime varchar(255),Counter smallint,Device varchar(255), Source varchar(255), Description varchar(255),PRIMARY KEY (ID))"; //YOUR SQL COMMAND TO CREATE A TABLE
SqlCommand create = new SqlCommand(createString, myConn);
myConn.Open();
create.ExecuteNonQuery();
myConn.Close();
return true;
}
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
using (var oCommand = new SqlCommand("SELECT * From storage WHERE ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
//Deletes the database by a query statement
//a return value of true means the delete was succesful
public static bool deleteDatabase()
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = #"ALTER DATABASE MyDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE [MyDatabase]";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
return true;
}
}
DON'T create another database, or table, it's evil. Just add Instance ID into table storage. And when writing new logs just add instance ID, same goes when reading from DB, put instance ID into where clause.
Another issue is to pick good Instance ID, your scenario is not very clear to me, but if you want every new application instance to have separate data, just create new GUID and use it as Instance ID.
For example you can have static property InstanceID in your Database class, and your class could look something like this :
public class Database
{
public static Guid InstanceID = new Guid();
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, InstanceID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
// writing InstanceID
cmd.Parameters.AddWithValue("#InstanceID", Database.InstanceID);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
// select with InstanceID
using (var oCommand = new SqlCommand("SELECT * From storage WHERE InstanceID = #InsID ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
oCommand.Parameters.AddWithValue("#InsID", Database.InstanceID);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
}
btw. DON'T swallow exceptions ! I leave your code the same but please don't do that, it's also evil, another thing is if there is a exception in your addElement method your connection will not be closed, use Using statement.
that doesn't sound safe at all, maybe one database with several user tables to store the logfiles for each user, but this just doesn't sound right to me.
otherwise a variable that is assigned randomly when the application is started in place of the database name when it is created.
but if you do something wrong there are going to be a lot of databases out there, but it looks like you have figured out sizing and some other things to keep them from overpowering the server machine.
Additional Information from Comment
if you are going to use tables on the Database(which I think is what you really need) then create the database separate and then create randomly named tables inside your application every time it is opened, you may want to have another table that would keep track of the the tables and the times they were opened as well, perhaps even what user opened them and such things like that
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;
}
}