简体   繁体   English

如何使用 C# 检查 .sqlite 文件中的表是否存在

[英]How to check if a table within a .sqlite file exists using C#

I am creating a WPF program where the user can create lists of products that are stored in an .sqlite database.我正在创建一个 WPF 程序,用户可以在其中创建存储在 .sqlite 数据库中的产品列表。 Each product list has it's own table inside the database, who's name is chosen by the user.每个产品列表在数据库中有自己的表,名称由用户选择。 I need to figure out if the table already exists when I try to create them so that if they do I can ask the user to choose a different name.当我尝试创建它们时,我需要弄清楚该表是否已经存在,以便如果存在,我可以要求用户选择不同的名称。

I know我知道

SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';

is the query used to check if a table exists but how do I get this statement in boolean form using c#?是用于检查表是否存在的查询,但如何使用 c# 以布尔形式获取此语句?

I would assume something similar to我会假设类似于

SQLiteConnection connection = new SQLiteConnection("Data Source=filepath;Version=3");
sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';"
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.something();

But I am unsure what function of command to use to get the Boolean value of this query and how to format it.但我不确定使用什么command函数来获取此查询的布尔值以及如何对其进行格式化。

ExecuteNonQuery() returns -1 for SELECT statements, so it would be inappropriate to use it in this case. ExecuteNonQuery()为 SELECT 语句返回 -1,因此在这种情况下使用它是不合适的。

try using ExecuteReader() , which returns a SqliteDataReader class that contains the HasRows property, in which should be true in case of a non-empty result set.尝试使用ExecuteReader() ,它返回一个包含HasRows属性的SqliteDataReader类,在非空结果集的情况下应该为真。

the code:编码:

SQLiteConnection connection = new SQLiteConnection("Data Source=filepath;Version=3");
sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';"
SQLiteCommand command = new SQLiteCommand(sql, connection);

try 
{
  var result = command.ExecuteReader();

  if (result.HasRows) 
  {
    // INSERT statement here
  }

}
catch (Exception e) 
{
  throw e;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM