200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > c#下各种数据库操作的封装!(支持ACCESS SQLSERVER DB2 ORACLE MYSQL)(二)

c#下各种数据库操作的封装!(支持ACCESS SQLSERVER DB2 ORACLE MYSQL)(二)

时间:2021-06-03 06:59:39

相关推荐

c#下各种数据库操作的封装!(支持ACCESS SQLSERVER DB2 ORACLE MYSQL)(二)

使用静态工厂模式,通过传入枚举型参数,动态创建访问实例

实现模式上采用基本实现接口,派生类继承基类的虚函数,从而实现代码的耦合较低,有很好的扩展性。

publicenum DBType

...{

Access,

SQL,

DB2,

Oracle,

MySQL

}

publicstaticclass DBAccessFactory

...{

publicstatic IDBAccess Create(DBType type)

...{

IDBAccess IRet = null;

switch (type)

...{

case DBType.Access:

IRet = new Access(type);

break;

case DBType.SQL:

IRet = new SQL(type);

break;

default:

break;

}

return IRet;

}

privateabstractclass DBAccess : IDBAccess

...{

protected DbConnection m_oConn = null;

protectedconststring CON_strServer = "Server";

protectedconststring CON_strDataBase = "Data Source";

protectedconststring CON_strUser = "UID";

protectedconststring CON_strPwd = "PWD";

protectedconststring CON_strConnTimeOut = "Connect Timeout = 2";

private DBType m_eDBType = DBType.Access;

protected DBAccess(DBType type)

...{

this.m_eDBType = type;

}

public DBType DBType

...{

get...{ returnthis.m_eDBType; }

}

publicvoid Init(string strServer, string strDataBase, string strUser, string strPwd)

...{

this.InitConn(strServer, strDataBase, strUser, strPwd);

}

publicvoid Open()

...{

if (this.m_oConn != null)

...{

this.m_oConn.Open();

}

}

publicint RunNoQuery(string strCmd)

...{

int iRet = 0;

try

...{

DbCommand oCmd = this.GetCmd(strCmd);

if (oCmd != null)

...{

iRet = oCmd.ExecuteNonQuery();

}

}

catch (Exception ex)

...{

throw (new Exception(ex.Message));

}

return iRet;

}

publicint GetFiledMax(string strTable, string strField)

...{

int iRet = -1;

DataTable dt = this.RunQuery("Select Max(" + strField + ") From " + strTable);

if (dt != null && dt.Rows.Count == 1)

...{

iRet = dt.Rows[0][0] is DBNull ? 0 : Convert.ToInt32(dt.Rows[0][0]);

}

return iRet;

}

public DataTable RunQuery(string strCmd)

...{

DataTable dt = new DataTable();

DbDataAdapter adp = this.DbAdp;

adp.SelectCommand = this.GetCmd(strCmd);

adp.Fill(dt);

return dt;

}

publicvoid Close()

...{

if (this.m_oConn != null && this.m_oConn.State == System.Data.ConnectionState.Open)

...{

this.m_oConn.Close();

}

}

publicbool TestConn()

...{

bool bRet = true;

try

...{

if (this.m_oConn.State != System.Data.ConnectionState.Open)

...{

this.m_oConn.Open();

}

bRet = this.m_oConn.State == System.Data.ConnectionState.Open;

}

catch

...{

bRet = false;

}

this.Close();

return bRet;

}

publicabstract DataTable Tables ...{ get; }

publicabstract DataTable GetColumns();

publicabstract DataTable GetColumns(string strTable);

protectedabstractvoid InitConn(string strServer, string strDataBase, string strUser, string strPwd);

protectedabstract DbCommand GetCmd(string strCmd);

protectedabstract DbDataAdapter DbAdp ...{ get;}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。