0% found this document useful (0 votes)
29 views7 pages

Class Private Private String Private String Private String Private String

The class DBConnect defines methods for connecting to a MySQL database and executing SQL statements. It contains private fields for the connection string details and a public constructor to initialize the connection. Methods are defined to open and close the database connection, as well as to insert, update, delete, select records, and get a row count. The select and count methods demonstrate using a data reader and ExecuteScalar respectively to retrieve and process results.

Uploaded by

Zicky Achmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views7 pages

Class Private Private String Private String Private String Private String

The class DBConnect defines methods for connecting to a MySQL database and executing SQL statements. It contains private fields for the connection string details and a public constructor to initialize the connection. Methods are defined to open and close the database connection, as well as to insert, update, delete, select records, and get a row count. The select and count methods demonstrate using a data reader and ExecuteScalar respectively to retrieve and process results.

Uploaded by

Zicky Achmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

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 = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE="
+
database + ";" + "UID=" + uid + ";" + "PASSWORD=" +
password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
}
//Close connection
private bool CloseConnection()
{
}
//Insert statement
public void Insert()
{
}
//Update statement
public void Update()
{
}

//Delete statement
public void Delete()
{
}
//Select statement
public List <string> [] Select()
{
}
//Count statement
public int Count()
{
}
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}

//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;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}

Working with DML (Insert, Update, Select, Delete)

Usually, Insert, update and delete are used to write or change


data in the database, while Select is used to read data.
For this reason, we have different types of methods to execute
those queries.
The methods are the following:
ExecuteNonQuery: Used to execute a command that will not
return any data, for example Insert, update or delete.
ExecuteReader: Used to execute a command that will return 0
or more records, for example Select.
ExecuteScalar: Used to execute a command that will return only
1 value, for example Select Count(*).
I will start with Insert, update and delete, which are the

1
2
3

4
5

easiest. The process to successfully execute a command is as


follows:
Open connection to the database.
Create a MySQL command.
Assign a connection and a query to the command. This can be
done using the constructor, or using the Connection and the
CommandText methods in the MySqlCommand class.
Execute the command.
Close the connection.
Hide Shrink

Copy Code

//Insert statement
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John
Smith', '33')";
//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()
{
string query = "UPDATE tableinfo SET name='Joe', age='22'
WHERE name='John Smith'";
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;

//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Delete statement
public void Delete()
{
string query = "DELETE FROM tableinfo WHERE name='John
Smith'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query,
connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}

1
2
3

4
5
6
7
8

To execute a Select statement, we add a few more steps, and we


use the ExecuteReader method that will return a dataReader
object to read and store the data or records.
Open connection to the database.
Create a MySQL command.
Assign a connection and a query to the command. This can be
done using the constructor, or using the Connection and the
CommandText methods in the MySqlCommand class.
Create a MySqlDataReader object to read the selected
records/data.
Execute the command.
Read the records and display them or store them in a list.
Close the data reader.
Close the connection.
Hide Shrink

//Select statement
public List< string >[] Select()
{
string query = "SELECT * FROM tableinfo";
//Create a list to store the result
List< string >[] list = new List< string >[3];
list[0] = new List< string >();

Copy Code

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
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["name"] + "");
list[2].Add(dataReader["age"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}

1
2
3

Sometimes, a command will always return only one value, like for
example if we want to count the number of records, we have been
using Select Count(*) from tableinfo;, in this case, we will
have to use the method ExecuteScalar that will return one
value.
The process to successfully run and ExecuteScalar is as
follows:
Open connection to the database.
Create a MySQL command.
Assign a connection and a query to the command. This can be
done using the constructor, or using the Connection and the
CommandText methods in the MySqlCommand class.
Execute the command.

5
6

Parse the result if necessary.


Close the connection.
Hide Copy Code

//Count statement
public int Count()
{
string query = "SELECT Count(*) FROM tableinfo";
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query,
connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar()+"");
//close Connection
this.CloseConnection();
return Count;
}
else
{
return Count;
}
}

You might also like