Sunday, December 1, 2019

Database Connectivity






create this method:

private Boolean connectedToDB()
{
  try
  {
     String strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\dbStudents.accdb;Persist Security Info=False;";
                
     Conn.ConnectionString = strConn;
     Conn.Open();
     return true;
  }
  catch (Exception ex)
  {
     MessageBox.Show("There's an error while connecting to the database.\n\n" + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
     return false;
  }
}

To call this method:

if (!connectedToDB())
   return;


==========================================================

Connection String (MS Access)

OleDbConnection Conn = new OleDbConnection();
String strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data  Source=c:\\dbms\\dbStudents.accdb;Persist Security Info=False;";
Conn.ConnectionString = strConn;
Conn.Open();

The Command Object

string strSQL = "INSERT INTO tblStudents(Stud_Name, Stud_Address) VALUES(?,?)";
OleDbCommand cmdStudents = new OleDbCommand();

cmdStudents.Parameters.AddWithValue("Stud_Name", txtName.Text);
cmdStudents.Parameters.AddWithValue("Stud_Address", txtAddress.Text);

cmdStudents.Connection = Conn;
cmdStudents.CommandText = strSQL;
cmdStudents.ExecuteNonQuery();
Conn.Close();






No comments:

Post a Comment