how to make database connection in sqlserver 2005 in c#

Recommended Answers

All 3 Replies

Here is an example using the SQL Native driver:

using System;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;

namespace daniweb
{
  public partial class frmSql : Form
  {
    public frmSql()
    {
      InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
      const string connStr = "Data Source=apex2006sql;Initial Catalog=ServManLeather;Integrated Security=True;";
      const string query = "Select GetDate() As [Today], @@SERVERNAME as [ServerName]";
      DataTable dt;
      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          using (SqlDataReader dr = cmd.ExecuteReader())
          {
            dt = new DataTable();
            dt.Load(dr);
          }
        }
        conn.Close();
      }
      MessageBox.Show(string.Format("Rows {0:F0}", dt.Rows.Count));
    }

Here is an example using the OleDb driver for SQL server:

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Linq;
using System.Data.SqlClient;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.Diagnostics;

namespace daniweb
{
  public partial class frmOleDbGrid : Form
  {
    private DataTable dt;

    public frmOleDbGrid()
    {
      InitializeComponent();
    }

    private void BuildSql()
    {
      const string connStr = @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Scott;Data Source=apex2006sql";
      const string query = "Select * From Experiment";
      using (OleDbConnection conn = new OleDbConnection(connStr))
      {
        conn.Open();
        using (OleDbCommand cmd = new OleDbCommand(query, conn))
        {
          using (OleDbDataReader dr = cmd.ExecuteReader())
          {
            if (dt != null)
              dt.Dispose();
            dt = new DataTable();
            dt.Load(dr);
            dataGridView1.DataSource = dt;
          }
        }
        conn.Close();
      }
    }

I would recommend using the first piece of code / sql native.

commented: Helpfull as always +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.