C# 从ini读取SQL连接
我想从ini文件构建一个SQL Compact连接 在我的ini文件中,连接路径如下所示:C# 从ini读取SQL连接,c#,sql,C#,Sql,我想从ini文件构建一个SQL Compact连接 在我的ini文件中,连接路径如下所示: DataBasePath=D:/Database/TrainingDatabase.sdf 我的代码如下: public static SqlCeConnection conn = new SqlCeConnection(@"Data Source="+SQLPath); 我可以毫无问题地从ini文件中读取数据库路径,但由于以下错误,我无法打开连接: 数据库不能为null、空字符串或仅包含空格的字符串
DataBasePath=D:/Database/TrainingDatabase.sdf
我的代码如下:
public static SqlCeConnection conn = new SqlCeConnection(@"Data Source="+SQLPath);
我可以毫无问题地从ini文件中读取数据库路径,但由于以下错误,我无法打开连接:
数据库不能为null、空字符串或仅包含空格的字符串
好的,让我们假设您有一个名为CONNECTION.TXT的文本文件,其中包含以下文本
Data Source = ServerName
Initial Catalog = DatabaseName
Integrated Security = false
User Id = sa
Password = 123456
下面的代码将逐行读取您的文本文件
string serverName, databaseName, userId, password;
bool integratedSecurity;
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("C:\\CONNECTION.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Data Source"))
serverName = line.Replace("Data Source = ", "");
else if (line.Contains("Initial Catalog"))
databaseName = line.Replace("Initial Catalog = ", "");
else if (line.Contains("Integrated Security"))
integratedSecurity = Convert.ToBoolean(line.Replace("Integrated Security = ", ""));
else if (line.Contains("User Id"))
userId = line.Replace("User Id = ", "");
else if (line.Contains("Password"))
password = line.Replace("Password = ", "");
Console.WriteLine(line);
counter++;
}
file.Close();
在不了解您的环境和所使用的技术(WinForms、ASP.NET、WPF?)的情况下,我只能显示一个试图突出您的问题的伪代码 这一行可能在一个类中
public class MyApp
{
public static SqlCeConnection conn = new SqlCeConnection(@"Data Source="+SQLPath);
......
}
这使得conn
变量成为类级别的全局静态变量,在第一次使用类()之前的某个时间初始化。这意味着
SQLPath
变量也应该是静态变量,否则其他静态变量将无法使用它
所以我们需要
public class MyApp
{
public static string SQLPath = MyApp.GetPathFromINIFile();
public static SqlCeConnection conn = new SqlCeConnection(@"Data Source="+SQLPath);
......
public static string GetPathFromINIFile()
{
// read and return the path from the INI key
....
return dbPath;
}
}
但这真的很弱。如果在conn
初始化之后出于任何原因移动SQLPath
的初始化,您将得到初始错误,并且头部划痕开始
我只能建议删除这些静态全局变量(至少是SqlCeConnection),并仅在需要使用SqlCeConnection时为其创建一个局部变量
public class MyApp
{
public static string SQLPath = MyApp.GetPathFromINIFile();
public static string GetPathFromINIFile()
{
....
return dbPath;
}
public bool UpdateCustomerTable(Customer cs)
{
using(SqlCeConnection cnn = new SqlCeConnection(MyApp.SQLPath))
{
......
}
}
}
通过这种方式,在程序运行期间,您不会使资源保持活动状态,并避免跨越危险水域,如
静态字段初始化规则。首先确保返回值(通过读取文件)不为null或空,如果不为null或空,您可以调用.Trim()
以消除任何可能的空白。如果这是静态全局SqlCeConnection,那么如何初始化SQLPath字符串?我们需要查看代码。这只是.ini或.txt文件中的一个简单字符串操作。显示读取ini文件的代码。放置断点以验证是否正确读取ini文件。或者只使用一个配置文件和适当的类。好吧,好吧,但是OP说他在读取INI文件时没有问题