gpt4 book ai didi

mysql - 从使用不同数据库的 DbConnection 派生类

转载 作者:行者123 更新时间:2023-11-29 23:56:15 30 4
gpt4 key购买 nike

我计划编写一个可以同时适用于 SQL Server 和 MySQL 的 DataConnection 库。

由于SqlConnection和MySqlConnection都是从DbConnection派生的,所以我创建了一个派生自它的类MyDBConnection

这是我到目前为止的代码,

class MyDBConnection : DbConnection
{
private MyDBConnection connection;
public MyDBConnection(String connectionString, String dbType)
{
if (dbType == "SqlServer")
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
//return myDBConnection as SqlConnection;
}
else if(dbType == "MySql")
{
MySqlConnection mysqlConnection = new MySqlConnection(connectionString);
//return myDBConnection as mysqlConnection;
}
}
}

但是后来我陷入了如何进行的困境,这是否可行?

最佳答案

首先,我不会实现DBConnection,我会继承IDbConnection。您需要对您使用的所有内容(如命令、数据适配器、事务等)执行相同的操作。我不太擅长 C#,所以我将其从 VB 转换,希望它转换成功

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
class MyDBConnection : IDbConnection
{

public enum DBType
{
SqlServer,
MySql
}

private DBType _DbType;

private string _ConnString;
public MyDBConnection(String ConnectionString, DBType ConnType)
{
_DbType = ConnType;
_ConnString = ConnectionString;
}

public IDbTransaction BeginTransaction()
{

}

public IDbTransaction BeginTransaction(IsolationLevel il)
{

}


public void ChangeDatabase(string databaseName)
{
}


public void Close()
{
}

public string ConnectionString { get; set; }

public int ConnectionTimeout {

get { }
}

public IDbCommand CreateCommand()
{

}

public string Database {

get { }
}


public void Open()
{
}

public ConnectionState State {

get { }
}

#region "IDisposable Support"
// To detect redundant calls
private bool disposedValue;

// IDisposable
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue) {
if (disposing) {
// TODO: dispose managed state (managed objects).
}

// TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
// TODO: set large fields to null.
}
this.disposedValue = true;
}

// TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
//Protected Overrides Sub Finalize()
// ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
// Dispose(False)
// MyBase.Finalize()
//End Sub

// This code added by Visual Basic to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion

}

关于mysql - 从使用不同数据库的 DbConnection 派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25326394/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com