Connection string - DotNet and DataBase

Monday, 30 July 2018

Connection string



A connection string is a component of data providers which are under ADO.Net. Connection string establishes the communication between the .Net application and the database.
Using connection string we can communicate with different database servers like "SQL server, MySQL, ORACLE etc.."

SQL Server Connection string:

connetionString="Data Source=ServerName;Initial Catalog=DatabaseName;User ID=username;Password=password"

Here "ServerName" is the instance name of the SQL server and "DatabaseName" is the database which we want to connect with.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace EmployeeTimeSheet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=LAPTOP-XYZMNO;Initial Catalog=EmployeeData;User ID=sa;Password=123456");
            con.Open();
            SqlCommand cmd =new SqlCommand("SELECT * FROM EmployeeInfo",con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Employees");
            dgvEmployees.DataSource = ds.Tables[0];
            con.Close();
        }
    }
}

After initializing the connection string, we need to open the connection using "con.Open();" and after read the data we need to close the connection using  "con.Close();".


No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.