gpt4 book ai didi

c# - 如何在没有大条件的情况下创建兼容SQL Server和SQLite的DbCommand?

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:32 26 4
gpt4 key购买 nike

嗨,假设我有一个 C# 代码

private const string INSERT = "INSERT INTO Person VALUES (@FirstName, @LastName)";

public static DbCommand INSERTCOMMAND(IPerson person)
{
DbCommand command = null;
var sqlParams = new List<DbParameter>();

if(SQLManagerFactory.SQLManager is SQLServerManager)
{
command = new SqlCommand(INSERT);
sqlParams.Add(new SqlParameter("@FirstName", person.FirstName);
sqlParams.Add(new SqlParameter("@LastName", person.LastName);
}
else // SQLiteManager
{
command = new SQLiteCommand(INSERT);
sqlParams.Add(new SQLiteParameter("@FirstName", person.FirstName);
sqlParams.Add(new SQLiteParameter("@LastName", person.LastName);
}

command.Parameters.AddRange(sqlParams.ToArray());
return command;
}

哪个工作得很好。当然,在我的生产代码中,它更大并且有更多的位置可以为不同的命令执行类似的操作。

我的问题是有什么办法可以缩短这段时间吗?除了调用不同的构造函数之外,我不想复制和粘贴本质上做同样事情的代码。

非常感谢您。

最佳答案

像这样就好了,我省略了细节,但你可以弄明白:

private const string INSERT = "INSERT INTO Person VALUES (@FirstName, @LastName)";

public static DbCommand INSERTCOMMAND(IPerson person)
{
DbCommand command = null;
var sqlParams = new List<DbParameter>();
MySqlEnum sqlType = SQLManagerFactory.SQLManager is SQLServerManager ? MySqlEnum.SQLServer : MySqlEnum.sqlLite

if(sqlType == MySqlEnum.SQLServer)
command = new SqlCommand(INSERT);
else // SQLiteManager
command = new SQLiteCommand(INSERT);

sqlParams.Add(new CustomSqlParameter(sqlType ,"@FirstName", person.FirstName);
sqlParams.Add(new CustomSqlParameter(sqlType ,"@LastName", person.LastName);

command.Parameters.AddRange(sqlParams.ToArray());
return command;
}

CustomSqlParameter 的代码应该很明显

关于c# - 如何在没有大条件的情况下创建兼容SQL Server和SQLite的DbCommand?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31753682/

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