How to include :
1. Add Reference
2. Browse
3. Select File 'MySql.Data.dll'
at
C:\Program Files\MySQL\MySQL Connector Net
1.0.3\bin.\NET 1.1
4. You put code
using MySql.Data.MySqlClient;
Create a connection with mysql database :
MySqlConnection conn = new MySqlConnection("Network Address=localhost;" + "Initial Catalog='test';" +"Persist Security Info=no;" + "User Name='root';" + "Password=''");
After creating a connection string, to apply it and actually establish the connection, you must call the MySqlConnection.Open(). Its syntax is:
public void Open();
As you can see, this method doesn't take any argument.
The MySqlConnection object that calls it is responsible
to get the connection string ready. If the connection
fails, the compiler would throw a MySqlException exception.
If the connection string doesn't contain a data source or
server, the compiler would throw an
InvalidOperationException
exception.
After using a connection and getting the necessary information from it, you should terminate it. To close a connection, you can call the MySqlConnection.Close() method. Its syntax is:
This method is simply called to close the current connection. While you should avoid
calling the Open() method more than once if a connection is already opened, you can
call the Close() method more than once.
Select Data :
To read data from a mysql table add following code under a button .
MySqlConnection conn = new MySqlConnection("Network Address=localhost;" + "Initial Catalog='test';" +"Persist Security Info=no;" +
"User Name='root';" +
"Password=''");
MySqlCommand command = conn.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select name from student where id='1'";
conn.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string thisrow = "";
for (int i = 0; i < Reader.FieldCount;i++)
thisrow += Reader.GetValue(i).ToString() + ",";
MessageBox.Show(thisrow);
}
conn.Close();
Insert Data:
MySqlConnection conn = new MySqlConnection("Network Address=localhost;" + "Initial Catalog='test';" + "Persist Security Info=no;" + "User Name='root';" +"Password=''");
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "insert into student(name,address)values('sanjoy','kaunia')";
MySqlDataReader result = command.ExecuteReader();
MessageBox.Show("successfully inserted");
result.Close();
conn.Close();
Delete Data:
MySqlConnection conn = new MySqlConnection("Network Address=localhost;" + "Initial Catalog='test';" + "Persist Security Info=no;" +
"User Name='root';" +
"Password=''");
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "delete from student where id='1'";
MySqlDataReader result = command.ExecuteReader();
MessageBox.Show("successfully deleted");
result.Close();
conn.Close();
No comments:
Post a Comment