Showing posts with label C# Database. Show all posts
Showing posts with label C# Database. Show all posts

16 December 2008

C# MS Access Connection String OLE DB OleDbConnection

The Connection String for MS Access can be set as ;
 private constr =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdbfile.mdb;
Jet OLEDB:Database Password=yourpassword;";
And the C# code to connect to MS Access database ;
 public bool OpenConnection()
{
OleDbConnection con; con = new OleDbConnection(constr);

if (con.State != ConnectionState.Open)
{
try
{
con.Open(); return true;
}
catch (Exception) { return false; }
}
else return false;
}
C# Access Connection String OLE DB OleDbConnection password field is the password you set up in access database.

25 November 2008

C# ASP.NET MySQL Connection Tutorial with MySQL Connector

In order to connect to MySQL Server with .NET in C# or ASP.NET does not matter actually,
  • You need to download MySQL Connector/Net .
  • After you add a reference to your project, it is probably in C:\Program Files\MySQL\MySQL Connector Net 5.0.7\Binaries\.NET 2.0 folder, add the MySql.Data.dll file as a reference.
  • Make your connection string, the following code will shows a standard MySQL connection string.

using MySql.Data.MySqlClient;
public static string GetConnectionString()
{
string connStr =
String.Format("server={0};user id={1}; password={2};
database=yourdb; pooling=false", "yourserver",
"youruser", "yourpass");

return connStr;
}
  • Then create an instance from MySql.Data.MySqlClient.MySqlConnection as shown below.
  •  MySql.Data.MySqlClient.MySqlConnection mycon
    = new MySqlConnection( GetConnectionString());
  • Then Try to open the MySQL connection.
  • if(mycon .State != ConnectionState.Open)
    try
    {
    mycon .Open();
    }
    catch (MySqlException ex)
    {
    throw (ex);
    }
So simple as you see, It is always better to do this in data access layer also called DAL.
Connect Mysql in C# and ASP.NET.