Creating a Database Connection

by Shabbir on May 1, 2008

in C#

The database connection is so easy to do in .Net Framework.
We will use Microsoft Access database for our example, the code will be written in C#.Net.

For start create one Microsoft Access database (db.mdb), and create a table (Info) with the folowing columns

  • ID (AutoNumber)
  • FirstName (Text)
  • LastName (Text)

Then in button event (it's described here), add this code

string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb;";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connStr;
string cmdStr = "INSERT INTO Info (FirstName, LastName)" +
" VALUES('John', 'Smith');";
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

More connection strings for connecting to diferent databases from diferent interfaces you can find here. The connection string that we have used is to connect co Microsoft Access database from OleDb Connection.

When the event will be invoked, the program will try to connect to the database and insert the values 'John' in the column FirstName and 'Smith' in the column LastName. The ID will be increased by one automatically. And then the connection will be closed. The event can be invoked multiple times, then the records will duplicate.

The table will look like this, if the event is invoked 8 times

Database sample

Next time we will explain how to update the table dynamically.

Sharing is Caring...

Other Related Posts:

  1. Simple Data Entry In Microsoft Access Database
  2. ASP.Net Database Connection
  3. Creating a Windows Forms Application in C#
  4. Read/Write Registry Keys
  5. Adding Items to ListView Control

Leave a Comment

Spam protection by WP Captcha-Free

{ 2 trackbacks }

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.