把数据库连接字符串写入注册表
考虑到用户可能更换SQL Server服务器,所以数据库连接字符串不能写成固定的。我们可以把它写入一个文件,需要的时候访问它即可以了。
下面的方法是把它写入注册表(写入注册表是为了考虑到安全性,也可以写入某个xml文件)
using Microsoft.Win32;
private void SetRegistryKey(string name,string connstr)
{
RegistryKey rk=Registry.LocalMachine;
RegistryKey srk=rk.OpenSubKey("software",true);
if(srk.OpenSubKey("Sunsoft\SunWebExam")==null)
srk.CreateSubKey("Sunsoft\SunWebExam");
RegistryKey crk=srk.OpenSubKey("Sunsoft\SunWebExam",true);
crk.SetValue(name,connstr);
rk.Close();
srk.Close();
crk.Close();
}
{
RegistryKey rk=Registry.LocalMachine;
RegistryKey srk=rk.OpenSubKey("software",true);
if(srk.OpenSubKey("Sunsoft\SunWebExam")==null)
srk.CreateSubKey("Sunsoft\SunWebExam");
RegistryKey crk=srk.OpenSubKey("Sunsoft\SunWebExam",true);
crk.SetValue(name,connstr);
rk.Close();
srk.Close();
crk.Close();
}
private void btnSave_Click(object sender, System.EventArgs e)
{
string connString="packet size=4096;data source=";
//string connString="provider=SQLOLEDB;packet size=4096;data source=";
connString+=txtServer.Text.Trim()+";user id=";
connString+=txtUser.Text.Trim()+";pwd=";
connString+=txtPwd.Text.Trim()+";persist security info=False;initial catalog=SunWebExam";
//
//todo:写入注册表
//
SetRegistryKey("Server",connString);
this.DialogResult=DialogResult.OK;
this.Close();
}
{
string connString="packet size=4096;data source=";
//string connString="provider=SQLOLEDB;packet size=4096;data source=";
connString+=txtServer.Text.Trim()+";user id=";
connString+=txtUser.Text.Trim()+";pwd=";
connString+=txtPwd.Text.Trim()+";persist security info=False;initial catalog=SunWebExam";
//
//todo:写入注册表
//
SetRegistryKey("Server",connString);
this.DialogResult=DialogResult.OK;
this.Close();
}
/// <summary>
/// 打开数据库连接.
/// </summary>
private void Open()
{
// 打开数据库连接
if (con == null)
{
RegistryKey rk=Registry.LocalMachine;
RegistryKey subrk=rk.OpenSubKey("software\Sunsoft\SunWebExam");
string connString=(string)subrk.GetValue("server");
con = new SqlConnection(connString);
con.Open();
}
if(con.State ==System.Data.ConnectionState.Closed)
con.Open();
}
/// 打开数据库连接.
/// </summary>
private void Open()
{
// 打开数据库连接
if (con == null)
{
RegistryKey rk=Registry.LocalMachine;
RegistryKey subrk=rk.OpenSubKey("software\Sunsoft\SunWebExam");
string connString=(string)subrk.GetValue("server");
con = new SqlConnection(connString);
con.Open();
}
if(con.State ==System.Data.ConnectionState.Closed)
con.Open();
}