0

我遇到了一个奇怪的子字符串问题。显然,由于某种奇怪的原因,我得到的字符串无法转换为 Int32。当我尝试这样做时收到的错误消息是“输入字符串的格式不正确”。因此,我也无法将这些值插入数据库。

这是代码...

string width = GetMetadata(filename, 162); //returns "1280 pixels"
string height = GetMetadata(filename, 164); //returns "700 pixels"
width = width.Substring(0, width.IndexOf(' ')); //returns "1280"
height = height.Substring(0, height.IndexOf(' ')); //returns "700"

//test: "System.Convert.ToInt32(width)" will fail, giving error "input string was not in correct format"
//doing the above on "width" yields the same result

//fails, giving error "no such column: 1280" (underlying database is sqlite)            
Database.NonQuery("INSERT INTO image VALUES (" + fileid + ", " + width + ", " + height + ")"); 
4

2 回答 2

3

出于所有正常原因——主要是避免将数据转换留给数据库,并防止 SQL 注入攻击——我建议您在 C# 中执行对数字的解析,然后使用参数化查询与 SQLite 对话。

在这种情况下,这将使调试变得更加容易 - .NET 也将无法解析字符串(在这种情况下,它可能是您的数据有问题)或者它会工作,并且您不需要担心什么转换数据库正在执行。

编辑:我刚刚看到你的评论说这也Convert.ToInt32失败了。这是一个非常清楚的迹象,表明是数据导致了问题。

我希望您的代码看起来像这样:

string widthText = GetMetadata(filename, 162);
string heightText = GetMetadata(filename, 164);
widthText = width.Substring(0, width.IndexOf(' ')).Trim();
heightText = height.Substring(0, height.IndexOf(' ')).Trim();

int width = int.Parse(widthText, CulutureInfo.InvariantCulture);
int height = int.Parse(widthText, CulutureInfo.InvariantCulture);

using (SQLiteCommand cmd = Database.CreateCommand())
{
    cmd.CommandText = "INSERT INTO image VALUES (?, ?, ?)";
    cmd.Parameters.Add(fileid);
    cmd.Parameters.Add(width);
    cmd.Parameters.Add(height);
    cmd.ExecuteNonQuery();
}

请注意,该Trim调用将删除任何前导空格,这似乎是问题的原因。

于 2011-06-08T06:47:42.143 回答
0

字符串变量widthheight. Trim()在将字符串转换为整数之前调用字符串的方法:

width = width.Trim();
height = height.Trim();

希望这可以帮助。让我们知道。

于 2011-06-08T06:56:02.000 回答