Azri Zakaria
Azri Zakaria

Reputation: 1364

How to separate connection string and get connection string from a class in C#

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.

Upvotes: 1

Views: 2636

Answers (5)

UncleFifi
UncleFifi

Reputation: 895

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

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

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

Upvotes: 0

Muhammad Ibrar
Muhammad Ibrar

Reputation: 79

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.

Upvotes: 0

Steven
Steven

Reputation: 172616

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; 

Upvotes: 0

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28698

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;

Upvotes: 1

Sam Anwar
Sam Anwar

Reputation: 669

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.

Upvotes: 0

Related Questions