我试图使用MySQL,SQL服务器面临着奇怪的错误没有设置对SQL命令的对象工厂模式数据库连接
的实例
对象引用来实现对数据库的连接工厂模式对象
internal class SqlServerDB : IDatabase { private SqlConnection _Connection = null; private SqlCommand _Command = null; public IDbCommand Command { get { if (_Command == null) { _Command.Connection = (SqlConnection)Connection; //_Command = new SqlCommand(); } return _Command; } } public IDbConnection Connection { get { if (_Connection == null) { string connectionString = ConfigurationManager.ConnectionStrings["testSQL"].ConnectionString; _Connection = new SqlConnection(connectionString); } return _Connection; } } }
数据库制造部分:
public static class DatabaseFactory { public static IDatabase CreateDatabase(DBType type) { switch (type) { case DBType.SqlServer: return new SqlServerDB(); case DBType.MySql: return new MySQLDB(); } return null; } }
主要方法
static void Main(string[] args) { IDatabase database; DBType databaseType = DBType.SqlServer; database = DatabaseFactory.CreateDatabase(databaseType); IDbConnection connection = database.Connection; IDbCommand command = database.Command; command.CommandType = CommandType.Text; command.CommandText = "select * from User"; connection.Open(); }
和数据库的由枚举选择。
完美的男人谢谢你! –