Professional Documents
Culture Documents
Database Connection C# Handouts
Database Connection C# Handouts
Fields: id int
name varchar(255)
address varchar(50)
Open Visual Studio > New Project > Solution Explorer(F4) > right click on “REFERENCE” > all MySql.dll(win apps), MySql.web.dll(web
apps))
Add to header:
using MySql.Data.MySqlClient;
txtid txtname
DataGridView1
txtMobile
SOURCE CODE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication6
{
publicpartialclassForm1 : Form
{
String MyConnectionString =
"Server=localhost;Database=sampledatabase;Uid=root;Pwd="; public Form1()
{
InitializeComponent();
}
LoadData();
1
Prepared by: Rochelle B. Cadayong
{
cmd = connection.CreateCommand();
cmd.CommandText = "Insert into infotbl (id, name, address)values(@id, @name,@address)";
cmd.Parameters.AddWithValue("@id", int.Parse(txtid.Text));
cmd.Parameters.AddWithValue("@name", (txtname.Text));
cmd.Parameters.AddWithValue("@address", (txtaddress.Text));
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully Added!");
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
LoadData();
}
} }
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
LoadData();
}
}
2
Prepared by: Rochelle B. Cadayong
}
}
catch (Exception)
{
throw;
} }
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
LoadData();
}
}}
3
Prepared by: Rochelle B. Cadayong