SQL读取连接字符串

SQL读取连接字符串

本文介绍了SQL读取连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过使用所述.txt文件的直接路径从txt文件中读取连接字符串,而包含连接字符串。

is it possible to read the connection string from a txt file, by using the direct path of the said .txt file witch containts the connection string.

代码是以下内容,我有这行,我想读取.txt文件:

The code is the following, i have this line wich i want to read the .txt file:

SqlConnection conn = @"Data Source='C:\Users\Administrator\Desktop\connstring.txt'";

请说该txt文件是真正的连接字符串,这是这样的:

Instide the said txt file is the real connection string wich is this:

@"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";

我知道这可能不是很安全,但这只是一个学术练习,试图学习c#和sql 。

I know this might not be very safe but it's only an academical exercise, trying to learn c# and sql.

推荐答案

总之:不,不可能这样做。您需要一个对象,该对象首先可以从流中读取,使用该读取器获取连接字符串,然后将连接字符串传递给 SqlConnection 对象实例的构造函数。

In short: no, it is not possible to do it like this. You need an object that can read from a stream first, obtain you connection string using that reader and then pass the connection string to the constructor of your SqlConnection object instance.

string connectionString;
var path = @"C:\Users\Administrator\Desktop\connstring.txt";
using (StreamReader sr = new StreamReader(path))
{
    connectionString = sr.ReadLine();
}

var connection = new SqlConnection(connectionString);

这篇关于SQL读取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:21