Click here to Skip to main content
15,919,423 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hello,

I am new to C# and I am doing a simple project. I need help. how to save in SQL Server and retrieve the data by ID.

Thanks in advance,

Asgar :sigh:
Posted
Updated 29-Nov-10 1:20am
v3

Hi, aftab5124
can you help me with writing the search record code? Thanks in advance
 
Share this answer
 
Comments
[no name] 25-Jul-12 14:11pm    
How is this a solution to this almost 2 year old question?
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DataConnection
/// </summary>
public class DataConnection
{
    SqlConnection _connection = null;
    SqlCommand _cmd = null;
	public DataConnection()
	{
        _connection = new SqlConnection("Data Source=192.168.1.102\\serverpvt;Initial Catalog=aftab;User Id=sa;Password=abc123#");
        _connection.Open();
	}
    public void CloseConnection()
    {
        if (_connection != null)
        {
            _connection.Close();
            _connection = null;
        }
    }
    public int ExecuteQuery(string psql) //insert,update, delete
    {
        int affectedrows = 0;
        _cmd = new SqlCommand();
        _cmd.Connection = _connection;
        _cmd.CommandType = CommandType.Text;
        _cmd.CommandText = psql;
        affectedrows = _cmd.ExecuteNonQuery();
        return affectedrows;
    }
    public SqlDataReader FetchQuery(string psql)//select
    {
        _cmd = new SqlCommand();
        _cmd.Connection = _connection;
        _cmd.CommandType = CommandType.Text;
        _cmd.CommandText = psql;
        SqlDataReader sreader = _cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return sreader;
    }
    public SqlCommand CreateCommand(string sqlText, bool procedure)
    {
        _cmd = _connection.CreateCommand();
        _cmd.CommandText = sqlText;
        //cmd.Transaction = _transaction;
        if (procedure)
            _cmd.CommandType = CommandType.StoredProcedure;
        return _cmd;
    }
}
//above is dataConnection class
//suppose u want to save country name:
//Make countryHandler class:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
/// <summary>
/// Summary description for CountryHandler
/// </summary>
public static class CountryHandler
{
	
    public static DataTable GetAll_Country()
    {
        DataTable dt = new DataTable();
        DataConnection dcon = new DataConnection();
        SqlCommand cmd = dcon.CreateCommand("GetAll_CountryDetails", true);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        
        return dt;
    }
    public static DataTable Insert_Country(string pCountryName) 
    {
        DataTable dtInsert = new DataTable();
        DataConnection dcon = new DataConnection();
        SqlCommand cmd = dcon.CreateCommand("Insert_Country", true);
        cmd.Parameters.AddWithValue("@countryName", pCountryName);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dtInsert);
        return dtInsert;
    }
    public static DataTable Update_Country(string pCountryName, Int64 pCountryID)
    {
        DataTable dtInsert = new DataTable();
        DataConnection dcon = new DataConnection();
        SqlCommand cmd = dcon.CreateCommand("Update_Country", true);
        cmd.Parameters.AddWithValue("@countryName", pCountryName);
        cmd.Parameters.AddWithValue("@countryID", pCountryID);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dtInsert);
        return dtInsert;
    }
    public static DataTable GetCountryDetailsByCountryName(string pCountryName) 
    {
        DataTable dtCountryDetail = new DataTable();
        DataConnection dcon = new DataConnection();
        SqlCommand cmd = dcon.CreateCommand("Get_CountryDetail_By_CountryName", true);
        cmd.Parameters.AddWithValue("@countryName", pCountryName);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dtCountryDetail);
        return dtCountryDetail;
    }
}




//finally
protected void btnAddCountry_Click(object sender, EventArgs e)
    {
        try 
        {
            if (txtCountry.Text.ToString() != "")
            {
                DataTable dtCountryDetails = new DataTable();
                dtCountryDetails = CountryHandler.GetCountryDetailsByCountryName(txtCountry.Text.ToString());
                if (dtCountryDetails.Rows.Count !=0)
                {
                    if (dtCountryDetails.Rows.Count == 1) 
                    {
                        DataTable dtUpdate = CountryHandler.Update_Country(txtCountry.Text.ToString(),Convert.ToInt64(dtCountryDetails.Rows[0]["country_Id"]));
                        ShowMessageBox("Update Data.");
                        txtCountry.Text = "";
                        txtCountry.Focus();
                        LoadCounty();
                    }
                }
                else 
                {
                    DataTable dtInsert = CountryHandler.Insert_Country(txtCountry.Text.ToString());
                    ShowMessageBox("Save Data.");
                    txtCountry.Text = "";
                    txtCountry.Focus();
                    LoadCounty();
                }
            }
            else 
            {
                txtCountry.Text = "";
                txtCountry.Focus();
            }
        }
        catch (Exception ex) 
        {
            Response.Write(ex.Message);
        }
    }
 
Share this answer
 
v2
using System.Data;
using System.Data.SqlClient;

namespace myNamespace
{
class Program
{
Static void Main(string[]args)
{
SqlConnection con=new SqlConnection("server=yourservername;uid=sa;pwd=yourpassword;database=databasename");

//insert the information to the database

SqlCommand cmd=new SqlCommand("Insert into T1(Id,Name)values(@Id,@Name)",con);
Console.Write("Enter the Id:");
cmd.Parameters.Add("@Id",SqlDbType.Int).Value=Convert.ToInt32(Console.ReadLine());
cmd.Parameters.Add("@Name",SqlDbType.VarChar,30).Value=Console.ReadLine();
if(con.State==ConnectionState.Closed)
{
con.Open();
}
int i=cmd.ExecuteNonQuery();
if(i>0)
{
Console.WriteLine("Record Inserted Successfully");
}
else
{
Console.WriteLine("Operation Failed,Please Try Again Later");
}

//Get the information by Id

SqlDataAdapter dad=new SqlDataAdapter("Select * from T1 where Id=@Id",con);
Console.Write("Enter the Id to get the record:");
dad.SelectCommand.Parameters.Add("@Id",SqlDbType.Int).Value=Convert.ToInt32(Console.ReadLine());
DataTable dtbl=new DataTable();
dad.Fill(dtbl);
Console.WriteLine("Id:"+dtbl.Rows[0]["Id"].ToString());
Console.WriteLine("Name:"+dtbl.Rows[0]["Name"].ToString());

}
}
}
 
Share this answer
 
v3
Comments
Sajid Ahmed Shahsroha 19-Mar-11 7:53am    
whoever downvoted me plz could you tell me why ?? so that i can improve myself
You can see here[^] as well.
 
Share this answer
 
Comments
asgar ali 29-Nov-10 7:13am    
thanks buddy
Abhinav S 29-Nov-10 11:11am    
You are welcome.
 
Share this answer
 
Comments
asgar ali 29-Nov-10 7:10am    
thanks
Sebastien T. 29-Nov-10 9:45am    
The pleasure is for me :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900