Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
C# DB Connection Code Question
Message
From
17/04/2008 11:41:55
Timothy Bryan
Sharpline Consultants
Conroe, Texas, United States
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Miscellaneous
Thread ID:
01311457
Message ID:
01311466
Views:
21
Kevin,

That is a big question. Typically you would create your connection (Database Specific) access classes and call them from a factory method to allow you to create a different one for different databases. Then remove all the code in here that is specific to your application.

Again, a framework like Mere Mortals already does all this for you and is an excellent learning tool for understanding good coding practices. I have looked through the MM code extensively to learn these principles.

I am pretty sure you can get a demo version of many of the frameworks to try out and learn the process.

I can give you specific examples of data access classes if you wish, but they are not as good as the mm stuff.

Tim

>How do I make this routine generic so that I can connect to any type of database?
>
>
>public SqlConnection GetConnection()
>{
>
>    // Define variables
>    bool bTrustedConnection = true;
>    string sDatabase = "test";
>    string sPassword = "";
>    string sServer = "PC108\\SQLEXPRESS";
>    string sUserName = "";
>
>    // Define variables
>    string sConnString = "";
>
>    // If the user is trusted...
>    if (bTrustedConnection)
>    {
>        // Create the connection string for a trusted connection
>        sConnString = "Server=" + sServer + ";Database= " + sDatabase + ";Trusted_Connection=yes";
>    }
>    else
>    {
>        // Create the connection string for a logged in user
>        sConnString = "Server=" + sServer + ";Database= " + sDatabase + ";Uid=" + sUserName + ";Pwd=" + sPassword;
>    }
>
>    // Create a connection object, passing the connection string
>    SqlConnection oConnection = new SqlConnection(sConnString);
>
>    try
>    {
>        // Attempt to open the connection
>        oConnection.Open();
>    }
>    catch (Exception oException)
>    {
>        // Handle exception here
>    }
>
>    return oConnection;
>}
>
Timothy Bryan
Previous
Reply
Map
View

Click here to load this message in the networking platform