【问题标题】:Problems on retrieving data from sqlite3 in C#在 C# 中从 sqlite3 中检索数据的问题
【发布时间】:2017-09-08 19:15:36
【问题描述】:

我正在开发一个程序,这是我项目的一部分:在这段代码中,我需要从 sqlite3 DB 文件中接收 filenametweet 并将其存储到文件的扩展属性中。所以这是代码:

using Microsoft.WindowsAPICodePack.Shell;
using System;
using System.IO;    
using System.Data.SQLite;

class Program
{
    public static void Main()
    {
        var sqName = Path.Combine(Environment.GetFolderPath("~valid path~"));
        SQLiteConnection m_dbConnection;
        m_dbConnection =
        new SQLiteConnection("Data Source="+ sqName + ";Version=3;");
        m_dbConnection.Open();
        string sql = "SELECT * FROM TweetText";
        SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
        SQLiteDataReader reader = command.ExecuteReader();
        reader.Read();
        ShellFile.FromFilePath(reader["Filename"]).Properties.System.Comment.Value = reader["Tweet"];
    }
}

当我尝试构建它时,VS 2017 说我在 ShellFile.FromFilePath(reader["Filename"]).Properties.System.Comment.Value = reader["Tweet"] 上有错误,错误代码是:

CS1503 参数 1:无法从 'object' 转换为 'string'。

但有趣的是,如果我用如下错误替换该行,它会起作用:

Console.Write(reader["Filename"]);
Console.Write(reader["Tweet"]);

所以我的问题是,为什么 C# 在第一个代码中将 reader["Filename"] 识别为对象,而在第二个代码中将 reader["Filename"] 识别为字符串?我该如何解决这个问题?

【问题讨论】:

    标签: c# sqlite


    【解决方案1】:

    Console.Write 有多个重载。其中之一承认对象作为参数。在内部,Console.Write 将调用 reader["fieldname"] 返回的对象的 ToString() 方法。 reader["fieldname"] 正在返回底层数据库类型。 c# 编译器抱怨 'object' 到 'string' 之间的转换。

    你可以改变

    ShellFile.FromFilePath(reader["Filename"]).Properties.System.Comment.Value = reader["Tweet"];
    

    通过

    ShellFile.FromFilePath(reader["Filename"].ToString()).Properties.System.Comment.Value = reader["Tweet"].ToString();
    

    【讨论】:

    • 哦,我不知道 Console.Write 有多个重载。非常感谢!!效果很好。
    • 如果你觉得这个答案有用,别忘了用向上箭头投票!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多