C# how to insert data to mysql using C#? - c#

Im very new on C#
I Only create 1 Form that Can insert Data to Mysql Database. My code not have Error, but data cant enter the Database. I m so confused.
this my code
Koneksi.cs
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Windows.Forms;
namespace timbangan
{
public class Koneksi
{
public MySqlConnection konek;
//string konfigKoneksi = "server=localhost; database=timbangan; uid=root; pwd=";
string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public void bukaKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
var temp = konek.State.ToString();
if (temp == "Open")
{
MessageBox.Show(#"Connection working.");
}
else {
MessageBox.Show(#"Please check connection string");
}
}
public void tutupKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Close();
}
}//end of koneksi
}//end namespace
Isidata.cs File
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace timbangan
{
public class Isidata
{
MySqlDataAdapter adapter;
MySqlCommand komand;
Koneksi classKoneksi;
DataTable tabel;
string sql = "";
public DataTable tambahData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
classKoneksi = new Koneksi();
sql = "insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')";
//MessageBox.Show(sql);
tabel = new DataTable();
try
{
classKoneksi.bukaKoneksi();
komand = new MySqlCommand(sql);
adapter = new MySqlDataAdapter(sql, classKoneksi.konek);
adapter.Fill(tabel);
}
catch (Exception)
{
MessageBox.Show("error");
}
return tabel;
}
}//end of issdata
}//end of timbangan
Form1.cs File
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
namespace timbangan
{
public partial class Form1 : Form
{
public DataTable tabel;
public string status = "";
public string berat_filter, qty, nama_barang, dari, shift;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Isidata isi = new Isidata();
tabel = isi.tambahData(tbBerat.Text, tbQty.Text, tbNama.Text, tbDari.Text, tbShift.Text);
MessageBox.Show("Berhasil");
}
}
}
Can Anyone Help me to Fix this? or Advice me to have more short code to Insert data?
Thanks in advance

You could redesign your classes to something like this
namespace timbangan
{
public static class Koneksi
{
public static MySqlConnection konek;
private static string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public static MySqlConnection GetConnection()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
}
}//end of koneksi
public class Isidata
{
public int InsertData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
sql = #"insert into tb_timbang
(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT)
values (#berat_filter,#qty,#nama_barang,#dari,#shift)";
try
{
using(MySqlConnection cnn = Koneksi.GetConnection())
using(MySqlCommand cmd = new MySqlCommand(sql, cnn))
{
cmd.Parameters.Add("#berat_filter", MySqlDbType.VarChar).Value = berat_filter;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = qty;
cmd.Parameters.Add("#name_barang", MySqlDbType.VarChar).Value = nama_barang;
cmd.Parameters.Add("#dari", MySqlDbType.VarChar).Value = dari;
cmd.Parameters.Add("#shift", MySqlDbType.VarChar).Value = shift;
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("error " + ex.Message);
return -1;
}
}
}
}//end of issdata
}//end of timbangan
In this design there are no more global variables around. The same Koneski class could be totally removed and your MySqlConnection could be created on the spot (reading the connectionstring from an external source like your config file). Don't think this is less efficient than keeping a global connection object already created and always open. There is an ADO.NET Connection Pooling infrastructure (link is for Sql Server but it is the same for MySql) that runs very efficiently to handle your connections
The important thing is the Using Statement (that closes and dispose the command and the connection when no more needed freeing valuable resources) and the parameters used to fill the command sent to the server. If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class
As a last note, notice that all parameters are of string type. This could work but it is best to have parameters of the same type of the field type on the database (and of course your variables should be of the correct datatype). This is particularly important with datetime fields that when are treated as strings could give a good headache to let them work correctly) See MySqlDbType enum

Make a class named DBClass.cs and write the below code-
class DBClass
{
MySqlCommand odcmd = new MySqlCommand();
MySqlConnection odcon = new MySqlConnection();
MySqlDataAdapter oda = new MySqlDataAdapter();
public DBClass()
{
}
public void OpenConnection()
{
odcon.ConnectionString = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
if (odcon.State == ConnectionState.Closed)
odcon.Open();
oda.SelectCommand = odcmd;
odcmd.Connection = odcon;
}
public void CloseConnection()
{
if (odcon.State == ConnectionState.Open)
odcon.Close();
}
public DataTable Select(string sql)
{
DataTable dt = new DataTable();
odcmd.CommandText = sql;
oda.Fill(dt);
return dt;
}
public int ModiFy(string sql)
{
odcmd.CommandText = sql;
return odcmd.ExecuteNonQuery();
}
}
On your form, Now you can fire your query like-
DbclassObject.Modify(Your_Insert_Update_Delete_Query);
DataTable dt= DbclassObject.Select(Your_Select_Query);

Related

make a label static error : cannot access a non-static member of outer type 'windowsForm8.Form1' via nested Type 'windowsForm8.Form1.DBConnect'

Yo this is my first post here and i wanna know how to fix this problem in C#
so im tryin to connect to database and select information from it and those information will be displayed as a label ! easy,
so this is the error i get :
cannot access a non-static member of outer type 'windowsForm8.Form1'
via nested Type 'windowsForm8.Form1.DBConnect'
and this is the Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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 = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
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)
{
//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:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//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()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = 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
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
please help me
,thanks :)
Move all your code from the class DbConnect yo your Form1 class. Then all of your methods have access to your form controls.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
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)
{
//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:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//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()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = 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
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
Like this your code ahould be able to access the labels, so it should compile. It still doesn't do anything since none of the methods are called.
Edited this on my phone, so couldn't test the code.

Registration allows duplicate user name in Access

I do have a problem in checking username and password in my registration form. When I tend to register the same username and password that's is already in my database(Access), still it allows to register. I just wanna trap it however, I don't know how to that.
What I want to output is that, I want a trap that says "Account Exists, Try Again!" or "Username Exists!"
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 System.Data.OleDb; using System.Text.RegularExpressions;
namespace Login { public partial class Register : Form {
private OleDbConnection personalConn;
private OleDbCommand oleDbCmd = new OleDbCommand();
private String connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public Register()
{
personalConn = new OleDbConnection(connParam);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
personalConn.Open();
oleDbCmd.Connection = personalConn;
if (textBox1.Text != "" && textBox2.Text != "")
{
int temp;
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
personalConn.Close();
}
}
catch (Exception)
{
MessageBox.Show("Invalid!, Duplicate Data.");
}
}
Notes: textBox1= username
textBox2= password Your attention is much highly appreciated. Thank you so much in advance.
Here is code which uses oledbcommand parameters using ? placeholder as mentioned in MSDN Reference. Also I have added using block which should Close opened connection implicitly.
using(OleDbConnection con = new OleDbConnection(connParam))
using(OleDbCommand cmd = new OleDbCommand("select count(*) from data where Users = ?"))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
object objRes = cmd.ExecuteScalar();
if (objRes == null || (int)objRes == 0)
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO data (Users,Pass) values(?, ?);";
cmd.Parameters.AddWithValue("#Users", textBox1.Text);
cmd.Parameters.AddWithValue("#Pass", textBox2.Text);
int iRes = cmd.ExecuteNonQuery();
if(iRes > 0)
MessageBox.Show("Registration Success!");
}
else
errorProvider2.SetError(textBox1, "This username has been using by another user.");
}
You almost never use data (in this case, a username) as the primary key for a record in a database. Chance are, your access database is set up the same way.
This means that there is nothing at the DBMS layer that will stop this from occurring, short of making the username the primary key (not recommended).
The solution is to perform a SELECT query to get the count of records with that username, and only allow the insert if the count is 0. You might be able to write a trigger to do this for you, and make the DBMS "reject" the insert, but given your (apparent) level with databases, I wouldn't try that at this point.
To get the count:
SELECT Count(*) FROM Users WHERE userName=#userName
A paramaterized query here is crucial to protect against SQL injection.
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 System.Data.OleDb;
using System.Text.RegularExpressions;
namespace Login
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(text1Box1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Mandatory fields password or user is empty");
retrun; //I'm not sure if this return is need. Remove it if MessageBox "breaks" the execution of the code below.
}
OleDbCommand cmd = new OleDbCommand(#"Select * from Data where User=#User");
cmd.Parameters.AddWithValue("#User", textBox1.Text);
DataSet dst = SqlManager.GetDataSet(cmd, "Data");
if(dst.Tables[0].Rows > 0)
{
MessageBox.Show("User already exist");
return; //again i'm not sure that this return is needed.
}
Insert("Data", "User", textBox1.Text, "Pass", textBox2.Text);
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need 1 class make it SqlManager.
public class SqlManager
{
private String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public static GetOleDbConnection(OleDbCommand cmd)
{
if(cmd.Connection == null)
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
Here is another method you can put in the form class:
public virtual void Insert(string TableName, params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
OleDbCommand cmd = new OleDbCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
Like other guys tell you use parameters in this case you will avoid sql injection. Read in wikipedia about it. Also I add some structure for your program, it is not perfect but I should write a lot for more. It is possible to have some typos here, because I wrote the code here. How you make the check, you fetch the data from database for the user which you write in textbox1.Text. If the dataSet have rows that means at the moment there is existing user with this name. If you don't know what is data set read System.Data.
You should learn to write data access in other classes !
Try this with your Existing Code :
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "') SELECT '" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "' WHERE NOT EXISTS(SELECT Users,Pass FROM data WHERE Users='" + this.textBox1.Text.ToString() +"');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
else
{
MessageBox.Show("Username is already Present !!!");
}
It returns 0 if the username is already present in data.

The "clsDataLayer" does not exists in current context

I have been trying to figure this out for hours now, I know there is some small error that I have here but I am not able to pinpoint it. Please help me.
So I created a class called "clsDataLayer.cs" and it is in the App_Code asp.net folder.
I then created a form called "frmUserActivity", but now when I post the code in it and call the class it says "The "clsDataLayer" does not exists in current context" Can anyone please help me?
code for clsDataLayer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Add your comments here
using System.Data.OleDb;
using System.Net;
using System.Data;
namespace ASP_PayRoll.App_Code
{
public class clsDataLayer
{
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// Add your comments here
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Add your comments here
DS = new dsUserActivity();
// Add your comments here
sqlDA.Fill(DS.tblUserActivity);
// Add your comments here
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Add your comments here
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
}
}
Code for frmUserActivity.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASP_PayRoll
{
public partial class frmUserActivity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Declare the DataSet
dsUserActivity myDataSet = new dsUserActivity();
//Fill the dataset with what is returned from the function
myDataSet = clsDataLayer.GetUserActivity(Server.MapPath("PayrollSystem_DB.mdb"));
//Sets the DataGrip to the DataSource based on the table
grdUserActivity.DataSource = myDataSet.Tables["tblUserActivity"];
//Binds the DataGrid
grdUserActivity.DataBind();
}
}
}
}
Thanks in advance.
Ak
Use ASP_PayRoll.App_Code.clsDataLayer. Your namespace in your data layer class is ASP_PayRoll.App_Code and in your page it's ASP_PayRoll.
Add using ASP_PayRoll.App_Code; to your aspx file.
Since you declared that in a namespace other than the one of your aspx page, you have to use a using statement, or the entire path (ASP_PayRoll.App_Code.clsDataLayer) in order to be able to access that class.

Why Am I getting this error in C# class?

Before anyone votes my question down, I would like to say that this is my first time using classes in C# and I have done a lot of research but I am still encountering errors. Newbie here.
I am trying to put the Insert, Delete, Update, and Count statements in a class file so that my code will be neat.
Here is the class file I made (with the help of research of course):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;
using System.Windows.Forms;
namespace classlib
{
public class DBConnect
{
private static MySqlConnection mycon;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "localhost";
database = "restaurantdb";
uid = "user";
password = "root";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
mycon = new MySqlConnection(connectionString);
}
private static bool OpenConnection()
{
try
{
mycon.Open();
return true;
}
catch (MySqlException ex)
{
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;
}
}
private static bool CloseConnnection()
{
try
{
mycon.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public static void Insert(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Update(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = mycon;
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Delete(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static int Count(string query)
{
int count = -1;
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
count = int.Parse(cmd.ExecuteScalar() + "");
CloseConnnection();
return count;
}
else
{
return count;
}
}
}
}
I was just trying the Count Method like in a certain form. Here is my code:
MessageBox.Show("NUMBER OF ACCOUNTS IN DATABASE = "+ DBConnect.Count("SELECT count(*) FROM usersettingsdb") +"", "CONFIRMATION");
But I get this error on the class file on the OpenConnection() method on the mycon.Open() line:
Object reference not set to an instance of an object.
How do I remove the said error and access the methods through calling it like so DBConnect.MethodName()?
I don't quite get anything about classes but I would really like to know how I can create my own functions/methods so as to keep my code neat.
Ok this is because you are messing up thing using in some cases static fields and in other cases not. There are tons of paper about static classes/members, see here for example.
The initialization code won't be called if you use the class as you are using.
In your case you should have a DBConnect instance and remove the static from methods
var db = new DBConnect();
and then use that in order to make queries:
db.Count(...);
Another solution is to call the Initialize method inside the Count method. You should modify Initialize in order to make it static (you will have to make all of your fields as static)
Another users will answer this question propably. So I want to mention different things. Your code is not very good. Instead of using it ,you can take a look at use of repository pattern. You can also use petapoco for database. These facilitate your work.
http://www.remondo.net/repository-pattern-example-csharp/
http://www.toptensoftware.com/petapoco/
Your myCon object is initialized in the Initialize() method, which is called in the constructor of the class, so only when you create an instance of DbConnect.
mycon = new MySqlConnection(connectionString);
In your code, you have no instance of DbConnect, you just call the static method Count of the class. So, the myCon is null.

How to refresh a Datagrid automatically if I'm using a List to collect information from Database?

I'm doing like a Mcdonalds' control panel to choose
what clients want to take. I'm doing it with Windows Forms
using C#. What I made was creating a class called products
and after in Form1.cs I made a List where I'll put the
products read from database.
I managed to do this and show the results on a DataGrid.
My problem is that when I make the selection of the products
and then I click on the button Send, the Datagrid doesn't refresh automatically. I have to close the program and when
i restart it i can see the changes.
My question is, does anyone know how to update de Datagrid
whitout restarting the program?
Thanks very much, I add my code below:
![]My_windows_form1
#
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
MySqlConnection conn = new MySqlConnection();
String connectionString = "Server=127.0.0.1; Database=mydatabase; Uid=root; Pwd=;";
List<products> listproducts = new List<products>();
public string product;
public string quantity;
public Form1()
{
InitializeComponent();
startConn();
}
private void startConn()
{
try
{
conn.ConnectionString = connectionString;
conn.Open();
textBox3.Text= "Correct connection";
//we call the function READ
read();
}
catch (MySqlException)
{
textBox3.Text="An error has ocurred";
}
}
public void read()
{
MySqlCommand instruccio = conn.CreateCommand();
instruccio.CommandText = "Select * from products";
MySqlDataReader search = instruccio.ExecuteReader();
while (search.Read())
{
products prod = new products();
prod.IdProd = search["idProd"].ToString();
prod.Name = search["nomProd"].ToString();
prod.Quantity = Int32.Parse(search["quantitat"].ToString());
listproducts.Add(prod);
}
dataGridView1.DataSource = listproducts;
search.Close();
search.Dispose();
}
private void btnEnviar_Click(object sender, EventArgs e) //Button Send (Enviar in spanish)
{
try
{
//before updating the stock in database we query the total quantity of the product selected
MySqlCommand instruccio1 = connexio.CreateCommand();
instruccio1.CommandText = "Select quantitat from productes where `nomProd`='"+ this.product +"'";
MySqlDataReader read = instruccio1.ExecuteReader();
int result = 0;
while (read.Read())
{
resultat=Int32.Parse(read["quantitat"].ToString());
}
read.Dispose();
instruccio1.Dispose();
if (this.quantity != 0)
{
if (result > this.quantity)
{
int difference = result - this.quantity;
MySqlCommand instruccio2 = conn.CreateCommand();
instruccio2.CommandText = "UPDATE products set `quantitat`='" + this.difference + "' where products.nomProd='" + this.product + "'";
instruccio2.ExecuteNonQuery();
conn.Close();
startConn();
textBox1.Text= "";
textBox2.Text = "";
this.quantity = "";
this.product = "";
}
else
{
MessageBox.Show("There's no quantity.");
}
}
catch (Exception xe)
{
MessageBox.Show("",xe.Message);
}
}
private void btnEsborrar_Click(object sender, EventArgs e) //Erase button
{
this.quantity = "";
this.product = "";
this.aEnviar = 0;
textBox1.Text = quantity;
textBox2.Text = product;
}
....
....
what you can do is the following:
Add a timer control on your form and set the time you want its Tick event to be fired, it is put in the Interval property in milliseconds.
on this event call your function startConn.
and thats it, very easy :)
In your read() method before
dataGridView1.DataSource = listproducts;
add
dataGridView1.DataSource = null;
Then call your startConn() method whenever you want.

Categories

Resources