Steve A
Steve A

Reputation: 1

Using local SQL database with c# forms

I am creating a small project on visual studio. I set up a local sql database that i can successfully initialize, open and access from one of my forms.

In my main form i use:

public static SqlCeConnection cn = new ...
cn.open(); //for opening the connection

SqlCeCommand cm = new SqlCeCommand("INSERT INTO ... etc

This works just fine. My question is how can i access the database from the next form as well? Should i declare and initialize again?

Sorry but i am very new to SQL and c#

Upvotes: 0

Views: 254

Answers (2)

susparsy
susparsy

Reputation: 1046

You use it like this:

public void foo()
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            using (SqlCommand command = new SqlCommand())
            {
                command.CommandText = "insert ...";

                command.Connection = connection;

                command.CommandType = CommandType.Text;

                command.Connection.Open();

                command.ExecuteNonQuery();

                ...
            }
        }
    }

Use 'using' with .net. it manages and closes the connections for you.

Upvotes: 0

Damith
Damith

Reputation: 63065

Don't share the connections, commands etc.. you better initialize when you need it.

read about using blocks and that will handle the closing connection and disposing objects.

Finally you can have separate class library for the Data Access related code and put all the database access methods in that class library. Then you can call methods on that class library from any of your Forms.

using (SqlCeConnection oConn = new SqlCeConnection(ConnectionString))
using (SqlCeCommand command = new SqlCeCommand("INSERT INTO ..", oConn ))
{
    oConn.Open();
    command.ExecuteNonQuery()     
}

Upvotes: 2

Related Questions