gpt4 book ai didi

c# - SQLite 中的变量

转载 作者:行者123 更新时间:2023-12-01 18:12:11 26 4
gpt4 key购买 nike

我想知道是否有一种已知的技术可以在 SqlLite 数据库中保存和使用变量。

我正在寻找类似 $something 变量的东西,可以在 Oracle 下找到

最佳答案

没有找到任何内置的解决方案,所以我通过使用带有键、值对的全局表来解决它

这是我为很好地包装它而制作的 C# 类

public class SQLiteVariable
{
public SQLiteVariable() : this (null, string.Empty)
{}
public SQLiteVariable(SQLiteConnection connection) : this(connection, string.Empty)
{}
public SQLiteVariable(string name) : this(null, name)
{}
public SQLiteVariable(SQLiteConnection connection, string name)
{
Connection = connection;
Name = name;
}

/// <summary>
/// The table name used for storing the database variables
/// </summary>
private const string VariablesTable = "__GlobalDatabaseVariablesTable";

/// <summary>
/// Gets or sets the SQLite database connection.
/// </summary>
/// <value>The connection.</value>
public SQLiteConnection Connection { get; set; }

/// <summary>
/// Gets or sets the SQLite variable name.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }

/// <summary>
/// Gets or sets the SQLite variable value.
/// </summary>
/// <value>The value.</value>
public string Value
{
get
{
CheckEnviornemnt();
var cmd = new SQLiteCommand(Connection)
{
CommandText = "SELECT Value FROM " + VariablesTable + " WHERE Key=@VarName"
};
cmd.Parameters.Add(new SQLiteParameter("@VarName", Name));
var returnValue = cmd.ExecuteScalar();
return returnValue as string;
}
set
{
CheckEnviornemnt();
// Assume the variable exists and do an update
var cmd = new SQLiteCommand(Connection)
{
CommandText = "INSERT OR REPLACE INTO " + VariablesTable + " (Key, Value) VALUES(@VarName, @Value)"
};
cmd.Parameters.Add(new SQLiteParameter("@Value", value));
cmd.Parameters.Add(new SQLiteParameter("@VarName", Name));
var count = cmd.ExecuteNonQuery();
}
}

private void CheckEnviornemnt()
{
if (Connection == null) throw new ArgumentException("Connection was not initialized");
var cmd = new SQLiteCommand(Connection)
{
CommandText = "CREATE TABLE IF NOT EXISTS "+VariablesTable+" (Key VARCHAR(30) PRIMARY KEY, Value VARCHAR(256));"
};
cmd.ExecuteNonQuery();
}
}

关于c# - SQLite 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1767466/

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