+ Reply to Thread
Results 1 to 2 of 2

Thread: Connect to SQL and do queries in C#

  1. #1

    Connect to SQL and do queries in C#

    I'd like a simple tutorial showing how to connect to a SQL database and do queries like insert , update and delete.

    Thanks in advance.
    Last edited by csharpmaster; 11-12-2012 at 02:02 AM.

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    36
    in this tutorial i`ll teach you how to connect to SQL server database and do queries like Insert , Update and Delete .

    First of all , you need to know your SQL-Server instance(Server Name) and to know it , you need to open SQL-Server Management Studio and look at Server Name , the default Server Name in is SQLSERVER or SQLSERVEREXPRESS based on your SQL-SERVER IDE version .

    For me the Server Name = .\ and Database Name = DB with table name info

    I created that SQL Sevrer table :
    Code:
    create table info(
    ID int not null,
    Info varchar(20)
    )
    We need to import the following Library :
    Code:
    using System.Data.SqlClient;
    First Step : [Connection String]
    Code:
    SqlConnection sqlcon = new SqlConnection("Data Source =./;Initial Catalog=DB;Integrated Security=True");
    Second Step : [Define SQL Data Adapter]
    Code:
    SqlDataAdapter sd = new SqlDataAdapter();
    [Insert data]
    Code:
                sd.InsertCommand = new SqlCommand("INSERT INTO info VALUES(@ID,@INFO)", sqlcon);
                sd.InsertCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = "2";
                sd.InsertCommand.Parameters.Add("@INFO", System.Data.SqlDbType.VarChar).Value = "info 2";
    
                // open connection and insert the above query
                sqlcon.Open();
                sd.InsertCommand.ExecuteNonQuery();
                sqlcon.Close();
    [Update data]
    Code:
                sd.UpdateCommand = new SqlCommand("UPDATE info SET Info=@INFO WHERE ID=1", sqlcon);
                sd.UpdateCommand.Parameters.Add("@INFO", System.Data.SqlDbType.VarChar).Value = "info 5";
    
                // open connection and insert the above query
                sqlcon.Open();
                sd.UpdateCommand.ExecuteNonQuery();
                sqlcon.Close();
    [Delete data]
    Code:
                sd.DeleteCommand = new SqlCommand("DELETE FROM info WHERE ID=2", sqlcon);
    
                // open connection and insert the above query
                sqlcon.Open();
                sd.DeleteCommand.ExecuteNonQuery();
                sqlcon.Close();

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts