Touseef Khan
Touseef Khan

Reputation: 443

how to make and use db connection class using csharp?

I am new to C# and OOP as well and am making a DB class to connect with SQL Server. Could you help me create a connection function and explain how to reuse it in many forms? I have seen a function from http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx but am unsure how to use it in another form.

Regards, Touseef

Upvotes: 1

Views: 42553

Answers (4)

gyousefi
gyousefi

Reputation: 351

If you mean DbConnection class, which is in the System.Data.Common namespace, then one way to use it in a C# program is as follows:

string CnnStr = "Data Source=local;Initial Catalog=dbTest;User Id=sa;pwd=1";
DbConnection cnn = new SqlConnection(CnnStr);
cnn.Open();

Upvotes: 1

Karuppasamy
Karuppasamy

Reputation: 11

Here are few code samples to get you going :

Establish the connection with SQL

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
SqlConnection con = new SqlConnection(connectionString);
con.Open();

//Database operations

con.Close();

Fetch the data from Database :

string queryString = "SELECT Column1, Column2 FROM TableName";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

DataSet customers = new DataSet();
adapter.Fill(customers, "myTable");

Hope this gets you going. All the best.

Upvotes: 1

AjayR
AjayR

Reputation: 4179

using System.Data.SqlClient;
//
    // First access the connection string, which may be autogenerated in Visual Studio for you.
    //
    string connectionString = "Write your sql connection string"
    //
    // In a using statement, acquire the SqlConnection as a resource.
    //
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        //
        // Open the SqlConnection.
        //
        con.Open();
        //
        // The following code shows how you can use an SqlCommand based on the SqlConnection.
        //
        using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
        using (SqlDataReader reader = command.ExecuteReader())
        {
        while (reader.Read())
        {
            // process it
        }
        }
    }

EDIT Use this link for detail tutorial http://www.codeproject.com/KB/database/sql_in_csharp.aspx

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176896

Make use of : C#: Microsoft Enterprise Library: Data Access

To make connection on the second form you need to close the first connection and than create new one on the other from to get data.

Upvotes: 0

Related Questions