嗨,只是出于我自己的好奇心的一个快速问题。我试图不重复我的代码。我仍在学习如何正确使用参数和参数,所以我想它会通过这条路线,这是我的代码。
public void MultiChoiceLight()
{
lCon = new SQLiteConnection(@"Data Source=knowledge.db;Version=3");
lCon.Open();
string query1 = $"UPDATE testOrder SET question='{QuestionsFromDb.question}', choice1='{QuestionsFromDb.choice1}" +
$"', choice2='{QuestionsFromDb.choice2}', choice3='{QuestionsFromDb.choice3}', choice4='{QuestionsFromDb.choice4}' " +
$"WHERE qid={QuestionsFromDb.b}";
lCmd = new SQLiteCommand(query1, lCon);
lCmd.ExecuteNonQuery();
lDr = lCmd.ExecuteReader();
lCon.Close();
}
public void MultiChoiceButtonNext()
{
lCon = new SQLiteConnection(@"Data Source=knowledge.db;Version=3");
lCon.Open();
string query = $"SELECT * FROM testOrder WHERE qid={qid}";
lCmd = new SQLiteCommand(query, lCon);
lCmd.ExecuteNonQuery();
lDr = lCmd.ExecuteReader();
}
好的,所以我想弄清楚的是,在每个方法中只使用一次代码行,然后在之后输入查询,这样我就可以通过一个方法尽可能多地执行此操作。我有很多这样的方法,真的很想缩短我的代码。在你说我知道 lambda 表达式和实体之前,但我没有在我试图制作的应用程序中使用它。如果我可以将我的查询保存到一个类文件中,然后从那里调用它们只是为了让我的代码看起来整洁,那就太好了。谢谢阅读。
您可以将您的 SQL 连接包装在某种帮助类中以及您需要的任何地方:
// TODO: Parametrized queries?
public class SQLConnectionHelper
{
private readonly string _connectionString;
// TODO: Parameterless constructor which gets connection string from config?
public SQLConnectionHelper(string connectionString)
{
_connectionString = connectionString;
}
private TResult WithConnection<T>(Func<SQLiteConnection, TResult> func)
{
// TODO: try-catch-rethrow-finally here
using (var connection = new SQLiteConnection(_connectionString))
{
_sqliteConnection.Open();
var result = func(_sqliteConnection);
_sqliteConnection.Close();
return result;
}
}
public void ConnectExecuteReader(string query, Action<SQLiteDataReader> action)
{
WithConnection(conn => {
var reader = new SQLiteCommand(query, conn).ExecuteReader();
action(reader);
});
}
public int ConnectExecuteNonQuery(string query)
{
return WithConnection(conn => {
return new SQLiteCommand(query, conn).ExecuteNonQuery();
});
}
}
用法:
public class YourClass
{
private readonly SQLConnectionHelper _sql = new SQLConnectionHelper(@"Data Source=knowledge.db;Version=3");
public void MultiChoiceLight()
{
string query1 = $"UPDATE testOrder SET question='{QuestionsFromDb.question}', choice1='{QuestionsFromDb.choice1}" +
$"', choice2='{QuestionsFromDb.choice2}', choice3='{QuestionsFromDb.choice3}', choice4='{QuestionsFromDb.choice4}' " +
$"WHERE qid={QuestionsFromDb.b}";
int result = _sql.ConnectExecuteNonQuery(query1);
}
public void MultiChoiceButtonNext()
{
_sql.ConnectExecuteReader($"SELECT * FROM testOrder WHERE qid={qid}", r => {
// process your reader here, outside of this lambda connection will be closed
});
}
}
好处:
SQLConnectionHelper
可以替换,客户端几乎SQLiteReader
是从特定类型的SQL连接中抽象出来的(除了,可以重写);CustomSQLException
,你只需要在一个地方定义它;SQLConnectionHelper
可以实现IDisposable
和清理连接资源。这个解决方案可能看起来有点过于“函数式”,因为使用了高阶函数,你可以用更 OOP 的方式重写它,它只是为了给出想法,而不是实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句