简体   繁体   English

如何从C#中的类中分离连接字符串并获取连接字符串

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

I'm newbie in C#. 我是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 . 因为每次我想编写代码时,都需要重新编写连接字符串并测试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# 这是我目前在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#. 希望您可以教我作为C#的新手。 Thanks for the help. 谢谢您的帮助。 And sorry for bad english. 对不起,英语不好。

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; 如果没有配置文件,请通过右键单击项目并“添加新项...”来添加一个。如果您正在编写Web应用程序,它将是一个web.config文件。 if you are writing a client app it will be an app.config file. 如果您正在编写客户端应用程序,它将是一个app.config文件。

You add a connection string to the configuration file in the connectionStrings node, normally at the top of the file. 您通常在文件顶部的connectionStrings节点中将连接字符串添加到配置文件。

<?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类来引用配置文件-如果还没有引用,则需要添加对System.Configuration的引用。

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

You're trying to reinvent the wheel here. 您正在尝试在这里重新发明轮子。 The .Net framework already include some simple techniques to handle this. .Net框架已经包含一些简单的技术来处理此问题。 If you're creating a Windows form project, you can store the connection string in App.Config using the connectionString attributes. 如果要创建Windows窗体项目,则可以使用connectionString属性将连接字符串存储在App.Config If this is a web app, then you store it in web.config , here is how it would look like: 如果这是一个Web应用程序,则将其存储在web.config ,如下所示:

<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: 然后,在您的代码中,从web.config中读取连接字符串,如下所示:

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#. 您在这里问的是一个非常基本的问题,它表明您正在试图欺负学习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. 我对您的建议是,抓住一本不错的C#书籍,并通过本书封面学习正确的方法。

Instead of putting the connection string into a separate file, store it in your app.config or web.config file. 无需将连接字符串放在单独的文件中,而是将其存储在app.config或web.config文件中。 .NET configuration files van contain a section that allows you to store connection strings: .NET配置文件包含一个允许您存储连接字符串的部分:

<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; 

I think Poster's question is pretty much valid. 我认为Poster的问题非常有效。 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. 尽管我们可以一次在Web.config或app.config中编写连接字符串并在整个项目中使用它,但是使用此技术存在一个缺点。 Connection string in web.config or app.config is never safe. web.config或app.config中的连接字符串永远都不安全。 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. 因此,最好在单独的类文件中使用连接字符串,然后在整个项目中使用它。

you could create a class which returns a sqlConnection... 您可以创建一个返回sqlConnection的类...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM