本文粗略的介绍了一种底层数据库连接方面的书写,它用到的主要知识是ADO.NET和C#。
// 私有的connection属性,数据对象内部使用.
private static SqlConnection mconUketsuke = null;
// 开放的connection属性,只读.
public static SqlConnection conUketsuke
{
get
{
if (mconUketsuke == null)
{
UketsukeConnect(false);
}
return mconUketsuke;
}
}
/// <summary>
/// 获取数据库连接串
/// </summary>
/// <param name="IpAddress">Ip地址</param>
/// <param name="DBName">数据库名</param>
/// <param name="UserName">用户名</param>
/// <param name="UserPwd">密码</param>
/// <returns>数据库连接字段</returns>
/// <remarks>
/// <programInfo>
/// </programInfo>
/// </remarks>
private static string CombinationConnectionStr(string IpAddress, string DBName, string UserName, string UserPwd)
{
string pConnectStr = "";
pConnectStr = "user " + "id=" + UserName + ";" + "password=" + UserPwd + ";"
+ "initial catalog=" + DBName + ";"
+ "data source=" + IpAddress + ";"
+ "Connect Timeout=" + "30";
return pConnectStr;
}
/// <summary>
/// 进行系统的连接测试,连接成功后会正常返回,不能连接时将抛出异常.<br/>
/// 在连接时需区分是否是在测试状态<br/>
/// 测试的意思是系统启动前测试是否连接数据库,初学者或做练习可以忽略if语句,事实上,下面的方法除去测试连接,我们可以很直观的看到,他只是做了一个简单的连接字符串的操作
/// </summary>
public static bool UketsukeConnect(bool bTest)
{
//如果是测试状态..
if (mconUketsuke != null && mconUketsuke.State.ToString() == "Open")
{
try
{
mconUketsuke.Close();
mconUketsuke = null;
//mcmdUketsuke = null;
}
catch (System.Exception ecp)
{
throw (ecp);
}
}
//下面用到的gUketsukeHost, SDUKETSUKE, gUketsukeUser, gUketsukePwd这几项读者自己定义和自己赋值,建议通过App.config或web.config文件的形式进行赋值
mconUketsuke = new SqlConnection();
mconUketsuke.ConnectionString =
CombinationConnectionStr(gUketsukeHost, SDUKETSUKE, gUketsukeUser, gUketsukePwd);
if (bTest)
{
try
{
mconUketsuke.Open();
}
catch (System.Exception ecp)
{
throw (ecp);
}
finally
{
if (mconUketsuke.State.ToString() == "Open")
{
mconUketsuke.Close();
}
}
try
{
mconUketsuke = null;
//mcmdUketsuke = null;
}
catch (System.Exception ecp)
{
throw (ecp);
}
}
return true;
}
-------------------截至到这里,connect连接就结束了,下面要做的是command的操作了,待续--------------------