You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 5.0中System.Data.Sqlite的ExecuteScalar返回null问题排查解决

问题背景
  • 开发环境:C# .NET 5.0、System.Data.Sqlite类库,Windows平台控制台应用
  • 核心需求:验证指定SQLite数据库中是否存在名为parcelas的数据表

使用的验证查询语句如下:

SELECT name FROM sqlite_master WHERE type='table' AND name='parcelas'
问题表现

上述SQL语句在DB Browser工具中运行正常,能返回正确结果,但在C#代码中执行时出现以下异常:

  1. SqliteCommand.ExecuteScalar()无显式报错,但返回null
  2. 读取返回结果时触发System.NullReferenceException,尝试对结果做类型转换、直接调用ToString()均无法解决问题

相关问题代码:

public void TableExist(string tableName)
{
    if (tableName == null || db == null || db.State != System.Data.ConnectionState.Open)
    {
        Console.WriteLine("ERROR!!!");
        return;
    }

    SQLiteCommand cmd = new SQLiteCommand(db);
    cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='"+ tableName +"'";
    var result = cmd.ExecuteScalar();
    Console.WriteLine("RESULT: " + result.ToString());
    return;
}
根因定位

问题根源为数据库路径配置错误:执行dbConnection.Open();时程序没有定位到目标数据库文件,SQLite默认会在指定路径自动创建一个空的数据库文件,空库中自然不存在parcelas表,导致查询返回空结果。

修复方案

可以从三个层面解决该问题:

  1. 连接字符串强制使用绝对路径
    避免相对路径受程序工作目录影响定位错误,示例:
// 拼接数据库绝对路径
string dbAbsolutePath = Path.Combine(AppContext.BaseDirectory, "your_target_db.db");
string connStr = $"Data Source={dbAbsolutePath};Version=3;";
  1. 禁止SQLite自动创建空库
    在连接字符串中添加FailIfMissing=True参数,当目标数据库不存在时直接抛出异常,避免静默创建空库导致逻辑异常,示例连接字符串:
Data Source=your_db_path;Version=3;FailIfMissing=True;
  1. 优化查询逻辑避免空引用异常
    对ExecuteScalar的返回结果先做非空判断再操作,同时可以将方法改造为返回布尔值明确表示表是否存在,优化后代码示例:
public bool TableExist(string tableName)
{
    if (string.IsNullOrWhiteSpace(tableName) || db == null || db.State != ConnectionState.Open)
    {
        Console.WriteLine("参数或数据库连接异常");
        return false;
    }
    // 使用参数化查询避免SQL注入风险
    using SQLiteCommand cmd = new SQLiteCommand(
        "SELECT name FROM sqlite_master WHERE type='table' AND name=@TableName", 
        db
    );
    cmd.Parameters.AddWithValue("@TableName", tableName);
    var result = cmd.ExecuteScalar();
    return result != null;
}

内容的提问来源于stack exchange,提问作者Iroqas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:39:03