i有一个databasemanager类,用于访问具有数据库名称和提供程序名称的数据库和常量类。 database和connectionstring工作正常,但提供程序名称为null,这会引发异常。 这是我的databasemanager类的代码
using System;
using System.Data;
/// <summary>
/// Summary description for ClsDataAccessLayer
/// </summary>
///
namespace MyAcademy.Forms
{
public class ClsDatabaseManager
{
#region [Member Variables]
private IDbConnection idbConnection;
private IDataReader idataReader;
private IDbCommand idbCommand;
private Constants.DataProvider providerType;
private IDbTransaction idbTransaction = null;
private IDbDataParameter[] idbParameters = null;
private string strConnection;
private string _ServerName;
private string _DatabaseName;
private string _UserID;
private string _Password;
private string _IntegratedSecurity;
#endregion
#region [Constructors]
public ClsDatabaseManager()
{
/*Default Constructor*/
ServerName = string.Empty;
DatabaseName = string.Empty;
UserID = string.Empty;
Password = string.Empty;
}
public ClsDatabaseManager(Constants.DataProvider providerType)
{
this.providerType = providerType;
}
public ClsDatabaseManager(Constants.DataProvider providerType, string
connectionString)
{
this.providerType = providerType;
this.strConnection = connectionString;
}
#endregion
public string ServerName
{
get { return _ServerName; }
set { _ServerName = value; }
}
public string DatabaseName
{
get { return _DatabaseName; }
set { _DatabaseName = value; }
}
public string UserID
{
get { return _UserID; }
set { _UserID = value; }
}
public string Password
{
get { return _Password; }
set { _Password = value; }
}
public string IntegratedSecurity
{
get { return _IntegratedSecurity; }
set { _IntegratedSecurity = value; }
}
private void SplitDatabaseConnectionString(string ConnectionString)
{
try
{
string[] ConParams = this.ConnectionString.Split(';');
foreach (string param in ConParams)
{
if (param.ToLower().Contains("database") || param.ToLower().Contains("initial catalog"))
{
DatabaseName = param;
DatabaseName = DatabaseName.Substring(DatabaseName.IndexOf('=') + 1, DatabaseName.Length - (DatabaseName.IndexOf('=') + 1)).Trim();
continue;
}
if (param.ToLower().Contains("data source") || param.ToLower().Contains("server"))
{
ServerName = param;
ServerName = ServerName.Substring(ServerName.IndexOf('=') + 1, ServerName.Length - (ServerName.IndexOf('=') + 1)).Trim();
continue;
}
if (param.ToLower().Contains("user") || param.ToLower().Contains("uid"))
{
UserID = param;
UserID = UserID.Substring(UserID.IndexOf('=') + 1, UserID.Length - (UserID.IndexOf('=') + 1)).Trim();
continue;
}
if (param.ToLower().Contains("password") || param.ToLower().Contains("pwd"))
{
Password = param;
Password = Password.Substring(Password.IndexOf('=') + 1, Password.Length - (Password.IndexOf('=') + 1)).Trim();
continue;
}
if (param.ToLower().Contains("integrated security"))
{
IntegratedSecurity = param;
IntegratedSecurity = IntegratedSecurity.Substring(IntegratedSecurity.IndexOf('=') + 1, IntegratedSecurity.Length - (IntegratedSecurity.IndexOf('=') + 1)).Trim();
continue;
}
}
}
catch { }
}
public static ClsDatabaseManager SplitDatabaseConnectionString(Constants.Databases eDatabase)
{
ClsDatabaseManager conString = new ClsDatabaseManager();
try
{
string str = null;
switch (eDatabase)
{
case Constants.Databases.Academy:
str = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
break;
case Constants.Databases.UniversityDB:
str = System.Configuration.ConfigurationManager.ConnectionStrings["UniversityDBCon"].ConnectionString;
break;
case Constants.Databases.HR_DB:
str = System.Configuration.ConfigurationManager.ConnectionStrings["HRMCon"].ConnectionString;
break;
case Constants.Databases.Inventory:
str = System.Configuration.ConfigurationManager.ConnectionStrings["Inventory"].ConnectionString;
break;
}
string[] arr1 = str.Split(';');
for (int i = 0; i < arr1.Length; i++)
{
string[] arr2 = arr1[i].Split('=');
switch (arr2[0])
{
case "Data Source":
conString.ServerName = arr2[1];
break;
case "Initial Catalog":
conString.DatabaseName = arr2[1];
break;
case "User ID":
conString.UserID = arr2[1];
break;
case "Password":
conString.Password = arr2[1];
break;
}
}
}
catch { }
return conString;
}
public static ClsDatabaseManager InitializeDbManager(Constants.Databases eDatabase = Constants.Databases.Academy)
{
string ConnectString = String.Empty;
switch (eDatabase)
{
case Constants.Databases.Academy:
try
{
ConnectString = Utility.Decrypt(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
}
catch
{
ConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
}
break;
case Constants.Databases.Account_DB:
try
{
ConnectString = Utility.Decrypt(System.Configuration.ConfigurationManager.ConnectionStrings["AccountDB"].ConnectionString);
}
catch
{
ConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["AccountDB"].ConnectionString;
}
break;
case Constants.Databases.HR_DB:
try
{
ConnectString = Utility.Decrypt(System.Configuration.ConfigurationManager.ConnectionStrings["HRMCon"].ConnectionString);
}
catch
{
ConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["HRMCon"].ConnectionString;
}
break;
case Constants.Databases.UniversityDB:
try
{
ConnectString = Utility.Decrypt(System.Configuration.ConfigurationManager.ConnectionStrings["UniversityDBCon"].ConnectionString);
}
catch
{
ConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["UniversityDBCon"].ConnectionString;
}
break;
case Constants.Databases.Inventory:
try
{
ConnectString = Utility.Decrypt(System.Configuration.ConfigurationManager.ConnectionStrings["Inventory"].ConnectionString);
}
catch
{
ConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["Inventory"].ConnectionString;
}
break;
}
string ProviderType = System.Configuration.ConfigurationManager.AppSettings["System.Data.SqlClient"];
Constants.DataProvider DP = (Constants.DataProvider)Enum.Parse(typeof(Constants.DataProvider), ProviderType);
ClsDatabaseManager dbManager = new ClsDatabaseManager(DP, ConnectString);
dbManager.SplitDatabaseConnectionString(ConnectString);
return dbManager;
}
#region [Properties]
public IDbConnection Connection
{
get
{
return idbConnection;
}
}
public IDataReader DataReader
{
get
{
return idataReader;
}
set
{
idataReader = value;
}
}
public Constants.DataProvider ProviderType
{
get
{
return providerType;
}
set
{
providerType = value;
}
}
public string ConnectionString
{
get
{
return strConnection;
}
set
{
strConnection = value;
}
}
public IDbCommand Command
{
get
{
return idbCommand;
}
}
public IDbTransaction Transaction
{
get
{
return idbTransaction;
}
}
public IDbDataParameter[] Parameters
{
get
{
return idbParameters;
}
}
#endregion
#region [Public Functions]
public void Open()
{
idbConnection =
ClsDatabaseManagerFactory.GetConnection(this.providerType);
idbConnection.ConnectionString = this.ConnectionString;
if (idbConnection.State != ConnectionState.Open)
idbConnection.Open();
this.idbCommand = ClsDatabaseManagerFactory.GetCommand(this.ProviderType);
}
public void Close()
{
if (idbConnection != null && idbConnection.State != ConnectionState.Closed)
idbConnection.Close();
}
public void Dispose()
{
GC.SuppressFinalize(this);
this.Close();
this.idbCommand = null;
this.idbTransaction = null;
this.idbConnection = null;
}
public void CreateParameters(int paramsCount)
{
idbParameters = new IDbDataParameter[paramsCount];
idbParameters = ClsDatabaseManagerFactory.GetParameters(this.ProviderType,
paramsCount);
}
public void AddParameters(int index, string paramName, object objValue, ParameterDirection direction = ParameterDirection.Input)
{
if (index < idbParameters.Length)
{
idbParameters[index].ParameterName = paramName;
idbParameters[index].Direction = direction;
idbParameters[index].Value = objValue;
}
}
public void AddParameters(int index, string paramName, object objValue, int size, ParameterDirection direction = ParameterDirection.Input)
{
if (index < idbParameters.Length)
{
idbParameters[index].ParameterName = paramName;
idbParameters[index].Direction = direction;
idbParameters[index].Value = objValue;
idbParameters[index].Size = size;
}
}
public void AddParameters(int index, string paramName, object objValue, DbType type, ParameterDirection direction = ParameterDirection.Input)
{
if (index < idbParameters.Length)
{
idbParameters[index].ParameterName = paramName;
idbParameters[index].Direction = direction;
idbParameters[index].Value = objValue;
idbParameters[index].DbType = type;
}
}
public void BeginTransaction()
{
if (this.idbTransaction == null)
idbTransaction = idbConnection.BeginTransaction();
//idbTransaction =
//ClsDatabaseManagerFactory.GetTransaction(this.ProviderType);
this.idbCommand.Transaction = idbTransaction;
}
public void BeginTransaction(IsolationLevel level)
{
if (this.idbTransaction == null)
idbTransaction = idbConnection.BeginTransaction(level);
//idbTransaction =
//ClsDatabaseManagerFactory.GetTransaction(this.ProviderType);
this.idbCommand.Transaction = idbTransaction;
}
public void CommitTransaction()
{
if (this.idbTransaction != null)
this.idbTransaction.Commit();
idbTransaction = null;
}
public void RollbackTransaction()
{
if (this.idbTransaction != null)
this.idbTransaction.Rollback();
idbTransaction = null;
}
public IDataReader ExecuteReader(string commandText, CommandType commandType = CommandType.StoredProcedure)
{
CloseReader();
this.idbCommand = ClsDatabaseManagerFactory.GetCommand(this.ProviderType);
idbCommand.Connection = this.Connection;
PrepareCommand(idbCommand, this.Connection, this.Transaction, commandType, commandText, this.Parameters);
this.DataReader = idbCommand.ExecuteReader();
idbCommand.Parameters.Clear();
return this.DataReader;
}
public void CloseReader()
{
if (this.DataReader != null && !this.DataReader.IsClosed)
this.DataReader.Close();
}
private void AttachParameters(IDbCommand command, IDbDataParameter[] commandParameters)
{
command.Parameters.Clear();
foreach (IDbDataParameter idbParameter in commandParameters)
{
if ((idbParameter.Direction == ParameterDirection.InputOutput)
&&
(idbParameter.Value == null))
{
idbParameter.Value = DBNull.Value;
}
command.Parameters.Add(idbParameter);
}
}
private void PrepareCommand(IDbCommand command, IDbConnection
connection,
IDbTransaction transaction, CommandType commandType, string
commandText,
IDbDataParameter[] commandParameters)
{
command.Connection = connection;
command.CommandText = commandText;
command.CommandType = commandType;
if (transaction != null)
{
command.Transaction = transaction;
}
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
}
public int ExecuteNonQuery(string commandText, CommandType commandType = CommandType.StoredProcedure)
{
CloseReader();
this.idbCommand = ClsDatabaseManagerFactory.GetCommand(this.ProviderType);
PrepareCommand(idbCommand, this.Connection, this.Transaction,
commandType, commandText, this.Parameters);
int returnValue = idbCommand.ExecuteNonQuery();
idbCommand.Parameters.Clear();
return returnValue;
}
public object ExecuteScalar(string commandText, CommandType commandType = CommandType.StoredProcedure)
{
CloseReader();
this.idbCommand = ClsDatabaseManagerFactory.GetCommand(this.ProviderType);
PrepareCommand(idbCommand, this.Connection, this.Transaction,
commandType, commandText, this.Parameters);
object returnValue = idbCommand.ExecuteScalar();
idbCommand.Parameters.Clear();
return returnValue;
}
public DataSet ExecuteDataSet(string commandText, CommandType commandType = CommandType.StoredProcedure)
{
CloseReader();
this.idbCommand = ClsDatabaseManagerFactory.GetCommand(this.ProviderType);
PrepareCommand(idbCommand, this.Connection, this.Transaction, commandType,
commandText, this.Parameters);
IDbDataAdapter dataAdapter = ClsDatabaseManagerFactory.GetDataAdapter
(this.ProviderType);
dataAdapter.SelectCommand = idbCommand;
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
idbCommand.Parameters.Clear();
return dataSet;
}
public DataTable ExecuteDataTable(string commandText, CommandType commandType = CommandType.StoredProcedure)
{
DataSet ds = ExecuteDataSet(commandText, commandType);
if (ds != null && ds.Tables.Count > 0)
return ds.Tables[0];
else
return null;
}
#endregion
internal void CreatePerameter(int p)
{
throw new NotImplementedException();
}
}
}
以下是constansts代码
using System;
/// <summary>
/// Summary description for Constants
/// </summary>
namespace Constants
{
public enum DataProvider
{
Oracle = 1,
SqlServer = 2,
OleDb = 3,
Odbc = 4
}
public enum Databases
{
Academy = 1,
UniversityDB = 2,
Account_DB = 3,
HR_DB=4,
Inventory=5
}
}
答案 0 :(得分:0)
您必须将值转换为其字符串表示形式。
string ProviderType = System.Configuration.ConfigurationManager.AppSettings [“System.Data.SqlClient”]。ToString();
上面的行应该是这样的
string ProviderType = System.Configuration.ConfigurationManager.AppSettings["connection"].ToString();