Illustrate the connection of c # program with database.
Here we assume MS-Access as database because of using Microsoft Access as the database is that it is a lightweight and user-friendly solution for small to medium-sized databases. It is relatively easy to set up and manage, and allows for quick prototyping and testing of database applications
establish a connection between a C# program and Microsoft Access database:
using System.Data.OleDb;
namespace AccessDatabaseDemo
{
class Program
{
static void Main(string[] args)
{
// Connection string to the Access database
string connectionString = @”Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\your_path_here\database.accdb”;
// Create a new connection
OleDbConnection connection = new OleDbConnection(connectionString);
// Open the connection
connection.Open();
// Do some database operations here…
// Close the connection when finished
connection.Close();
}
}
}
- Demonstrate the read and write operations from the database In C# programming.
Simple C# program that reads and writes data to a Microsoft Access database:
Let ,we have following database table in Ms Access
Field name | Data type |
id | Auto Number |
First Name | Text |
Last Name | Text |
Salary | Text |
Fig;Ms AccessDatabse : employee
using System;
using System.Data.OleDb;
namespace AccessDatabaseDemo
{
class Program
{
static void Main(string[] args)
{
// Connection string to the Access database
string connectionString = @”Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\your_path_here\database.accdb”;
// Create a new connection
OleDbConnection connection = new OleDbConnection(connectionString);
// Open the connection
connection.Open();
// Perform a SELECT query to read data from the database
OleDbCommand readCommand = new OleDbCommand(“SELECT * FROM employees”, connection);
OleDbDataReader reader = readCommand.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string firstName = reader.GetString(1);
string lastName = reader.GetString(2);
int salary = reader.GetInt32(3);
Console.WriteLine(“ID: {0}, Name: {1} {2}, Salary: {3}”, id, firstName, lastName, salary);
}
reader.Close();
// Perform an INSERT query to write data to the database
string newFirstName = “Ram”;
string newLastName = “Sharma”;
int newSalary = 500000;
OleDbCommand writeCommand = new OleDbCommand(“INSERT INTO employees (first_name, last_name, salary) VALUES (@firstName, @lastName, @salary)”, connection);
writeCommand.Parameters.AddWithValue(“@firstName”, newFirstName);
writeCommand.Parameters.AddWithValue(“@lastName”, newLastName);
writeCommand.Parameters.AddWithValue(“@salary”, newSalary);
int rowsAffected = writeCommand.ExecuteNonQuery();
if (rowsAffected > 0)
{
Console.WriteLine(“Employee added successfully!”);
}
else
{
Console.WriteLine(“No rows were affected.”);
}
// Close the connection
connection.Close();
// Wait for user input before exiting
Console.WriteLine(“Press any key to exit…”);
Console.ReadKey();
}
}
}