类型不作为条件

Typeof not working as condition

我目前有一种方法可以查看输入是什么类型的对象,并基于它创建一个 SQL 输入,就像这样:

private static string PropertyToDBString(object o)
{
    Debug.Log(o.GetType());
    if (o == typeof(System.String) || o == typeof(string))
        return "'" + o.ToString() + "'";
    else if (o == typeof(System.Boolean) || o == typeof(bool))
        return ((System.Boolean)o) ? "1" : "0";

    return "'" + o.ToString() + "'";
}

但这似乎不起作用,Everything returns as .toString() based, Boolean return as True/False, 但日志正在选择类型 system.boolean。像这样:

enter image description here

我正在使用 SQLite 并想知道我是否应该费心使用正确的数据类型,因为限制不存在,甚至事实上布尔列在数据库上是 INT(1) 但仍然存储True/False。我应该只对所有内容使用 TEXT 吗?

I currently have a method to see what type of object an input is and create a SQL input based on it

不要那样做。 请改用参数化 SQL。您应该 而不是 尝试格式化您的值以便在 SQL 中使用。这几乎 总是 将成为 SQL 注入攻击的途径。

现在,关于问题本身...您正在检查 o 本身是否为 typeof(bool) - 而我怀疑您想检查 o.GetType() 是否为 typeof(bool).

更好的是,使用 is 运算符:

if (o is string)
{
    return "'" + o + "'";
}
if (o is bool)
{
    bool value = (bool) o;
    return value ? "1" : "0";
}
// Are you sure you want this? I would throw an exception if you
// don't know what to do with the value...
return "'" + o + "'";

如果您在 SQL 中使用参数,则无需担心数据类型或单引号。

对于插入,而不是:

com.CommandText = "Insert into MyTable (ID,Name,Birthday,Age) values (12,'Bob','01/01/1980',24)";

你做到了:

com.CommandText = "Insert into MyTable (ID,Name,Birthday,Age) values (@ID,@Name,@BD,@Age)";
    int ID = 12;
    string Name = "Bob";
    DateTime Birthday = new DateTime(1980, 1, 1, 0, 0, 0);
    Int Age = 24;
    com.Parameters.AddWithValue("@ID", ID);
    com.Parameters.AddWithValue("@Name", Name);
    com.Parameters.AddWthValue("@BD", Birthday);
    com.Parameters.AddWithValue("@Age", Age);

对于布尔输入,您可以这样做:

bool isTrue = true;
    com.Parameters.AddWithValue("@isHappyCustomer",isTrue ? 1 : 0);

使用参数时,您不需要使用与数据库中相同的数据类型 - 只要值本身符合数据库字段的要求即可。因此,您可以将字符串发送到

这样的日期
com.Parameters.AddWithValue("@date","1/1/2016");

对于日期字段,或

com.Parameters.AddWithValue("@age","24");

对于 int 字段。虽然使用相同的数据类型而不依赖于 IMO 的这种转换功能总是一个好主意。