1

I'm newbie in C#. I want to ask, how can I separate the connection string config into a class?

Because every time I want to write code, I need to re-write the connection string and test the connection. So, I need to make a class so that every time I make a connection to the database, this class will test the connection first. Then after it works, the class will send the connection string to my coding. Besides, if I want to change my source data, I just need to change in the class only. No need to search all my coding

So if I can make a class, how do I call and get the connection string from class?

Can it be like that?

This is my current coding for connection string in C#

FileInfo file = new FileInfo(Application.StartupPath + "\\conn.txt");

if (file.Exists)
{
    StreamReader r = File.OpenText(Application.StartupPath + "\\conn.txt");
    connString = r.ReadToEnd();
    r.Close();

    // Open SQL connection
    SqlConnection openCon = new SqlConnection(connString);

    try
    {
        Cursor = Cursors.WaitCursor;
        openCon.Open();
    }
    catch
    {
        MessageBox.Show("Error to established connection\nPlease check Data Source");
        openCon.Close();
        Cursor = Cursors.Arrow;
    }
    else
    {
        MessageBox.Show("File config is missing");
    }
}

Hope you can teach me as a newbie in C#. Thanks for the help. And sorry for bad english.

1
  • If not clear, please tell me. :) Commented Sep 4, 2012 at 2:53

5 Answers 5

1

You should store connection strings in your configuration file. If you don't have a configuration file, add one by right-clicking the project and 'adding new item...' If you are writing a web app it will be a web.config file; if you are writing a client app it will be an app.config file.

You add a connection string to the configuration file in the connectionStrings node, normally at the top of the file.

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <!-- add a string -->
    <add name="MyConnectionString" 
         connectionString="Data Source=localhost; ... // etc 
         providerName="System.Data.SqlClient" />
  </connectionStrings>
  // and keep all the other configuration in the file

And then you simply refer to the configuration file using the ConfigurationManager class - you'll need to add a reference to System.Configuration if you don't already have one.

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Sign up to request clarification or add additional context in comments.

2 Comments

Hello @Kirk Broadhurst, After I deployment, Can I edit back in app.config? Thanks for help
@Chuki2 yes, you can edit the config file without the need to rebuild or redeploy. You might want to also check out appSettings which work the same way
0

You're trying to reinvent the wheel here. The .Net framework already include some simple techniques to handle this. If you're creating a Windows form project, you can store the connection string in App.Config using the connectionString attributes. If this is a web app, then you store it in web.config, here is how it would look like:

<connectionStrings>
      <add name="Prod" connectionString="Server=myServer;Database=DB1;user=sa;password=myPassword;Trusted_Connection=false" providerName="SQL" />
  </connectionStrings>

Then, in your code, you read the connection string from web.config as follow:

string connString = System.Configuration.ConfigurationManager.
    ConnectionStrings["Prod"].ConnectionString;

You're asking a very basic question here and it indicates that you're trying to bully your way into learning c#. My advice to you is to grab a good C# book and go through it cover to cover to learn things the right way.

3 Comments

It's a good question for a self-learner, though - I'm just amazed that I couldn't find a duplicate question.
Thanks for the help @sam Anwar, forgive me for asking a simple question. Because in the programming world there are so many way. Everyone is not the same way of thinking. So I try to find the easiest way to be a reference. Hope can forgive a novice like me. Hehe, thanks again!
No problems, it doesn't bother me asking a simple question. Any great engineer was also a novice at some point, but trust me, you'll develop much better techniques and avoid many unnecessary coding/design mistakes if you learn the fundamentals completely first. Best Regards...
0

Instead of putting the connection string into a separate file, store it in your app.config or web.config file. .NET configuration files van contain a section that allows you to store connection strings:

<connectionStrings>
    <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

You can retrieve this connection string using the following code:

string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; 

2 Comments

Hello @steven. It means,can I change the connection string after I deployment My Software?
Sure you can. Every part of your software csn be changed between deployments.
0

I think Poster's question is pretty much valid. Although we can write connection string in Web.config or app.config once and use it in whole project, but there is a drawback of using this technique. Connection string in web.config or app.config is never safe. These two files are ultimately like text files. There are ways to get the password from them. The security could be broken. So its better to use the connection string in a separate class file and get it in your whole project.

Comments

0

you could create a class which returns a sqlConnection...

public class DBConn
{
    private string ConnectionString = "123456789Connection";

    public SqlConnection getSqlConn()
    {
        return SqlConnection();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.