Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have a bit of code in each form to connected to SQL databases...

C#
private SqlConnection connectLink(string selectDbase)
        {
            SqlConnection returnCon = null;
            try
            {
                returnCon = new SqlConnection("Data Source=" + Properties.Settings.Default.sqlServer + ";"
                        + "Initial Catalog=" + selectDbase + ";"
                        + "Persist Security Info=True;"
                        + "User ID=" + Properties.Settings.Default.dBaseUname + ";Password=" + unScramble(Properties.Settings.Default.dBasePword));
            }
            catch
            {
                MessageBox.Show("There was an error connecting to the " + selectDbase + " Database");
            }
            return returnCon;
        }



Which I then call whenever I want to connect to a database...

C#
SqlConnection getDetails = connectLink(Properties.Settings.Default.linkDbase);


probably a dumb question but is there anyway I can have this sitting in a separate .cs file rather than in each forms code? I'm pretty new with C#...
Posted

Please see this article
General purpose class to fill DataTable(s) from DataBase and to save DataTable(s) to DataBase using reflection[^]
After instantiating the DataBaseConnector class with connection string it can be used at several places, to fill and save the data in DataTables
 
Share this answer
 
Microsoft created a class for exactly this purpose, named SqlHelper. The source code is here...

http://www.koders.com/csharp/fidD4121D6E4BCA2DAB656D770903FECBFF7427D242.aspx[^]

You don't have to keep creating SQL Connections with this class, you can just send it your connection string to one of the overloads. e.g.

C#
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"

// Get a dataset from a Straight text command
System.Data.DataSet results = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(connectionString, System.Data.CommandType.Text, "SELECT Field1 FROM Table5");


// Get a data reader from a stored procedure with parameters
int someParameter1 = 5;
string someParameter2 = "Test";
using (var reader = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(connectionString, "MyStoredProcedureName", someParameter1, someParameter2))
{
    while (reader.Read())
    {
        // do something
    }
}
 
Share this answer
 
 
Share this answer
 

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