How do I connect to a SQL database from C#?

Viewed 66471

I am trying to write a local program management and install system for my home network, and I think I've got the technologies nailed down:

  • C#/.NET/WPF for the client
  • Lua for installation scripting support (through LuaInterface)
  • SQL Server Express for maintaining a database of programs

However I'm unsure what specifically I'll use to connect C# to the database. Is there something built into the .NET framework for this? Bonus points if you have a suggestion on what I should use for interacting with said database.

9 Answers

You can use https://github.com/MohamadParsa/AdoDbConnection.Net and use the project as a project reference in your solution and enjoy. Also, you can explore DBConnection.cs file and copy class or method in your project. but ... for make a connection or disconnect to express you can use:

SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string _ErorrString = "";
string _InternalErorrString = "";
private void Connect()
{            
    cmd.Connection = con;
    da.SelectCommand = cmd;
    try
    {
        string cs = "";
        cs = @"Data source=.\SQLEXPRESS;Attachdbfilename=|DataDirectory|\" 
        + DataBbaseName + ".mdf;Integrated security=true;user Instance=true";
        con.ConnectionString = cs;
        con.Open();
    }
    catch (Exception ex)
    {
        _ErorrString += "Erorr NO. : 100" + ", connection error.";
        _InternalErorrString += ex.Message;
    }
}
private void Disconnect()
{
    con.Close();
}

and to execution command and get results:

public DataSet RunAndGet(string sql)
{
    //first, make a connection
    Connect();
    //to hold and return results
    DataSet dataSet = new DataSet();
    try
    {
        //set command
        cmd.CommandText = sql;
        //run and fill results into the dataset
        da.Fill(dataSet);
    }
    catch (Exception ex)
    {
        _ErorrString += "Erorr NO. : 101" + ", internal error.";
        _InternalErorrString += ex.Message;

    }
    //finally closes connection
    Disconnect();
    return dataSet;
}
Related