我的SQLiteParameters有什么问题?

时间:2016-12-09 10:30:56

标签: c# sqlite

我已将此功能用于将值插入数据库。它以前工作过。我唯一改变的是添加参数来处理输入。现在当我尝试使用它时,我收到此错误:SQLite error (1): near "@valuesParam": syntax error

请参阅下面的代码。我做错了什么?

    // Inserts value(s) into colum(s) of a certain table in the database.
    public void InsertToDatabase(string table, string columns, string values)
    {
        using (SQLiteConnection dbConnection = new SQLiteConnection(conString))
        {
            dbConnection.Open();

            using(SQLiteCommand insertionCommand = new SQLiteCommand(dbConnection))
            {
                insertionCommand.CommandText = "INSERT INTO " + table + " (" + columns + ") VALUES @valuesParam";
                insertionCommand.Parameters.AddWithValue("@valuesParam", values);
                insertionCommand.ExecuteNonQuery();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

@valuesParam不在命令的括号中...... 但是,我宁愿将插入的值作为列表传递

作为例子:

    public void InsertToDatabase(string table, string columns, List<string> values)
    {
        using (SQLiteConnection dbConnection = new SQLiteConnection(conString))
        {
            dbConnection.Open();

            using (SQLiteCommand insertionCommand = new SQLiteCommand(dbConnection))
            {
                insertionCommand.CommandText = "INSERT INTO " + table + " (" + columns + ") VALUES (";
                for (int i=0;i<values.Count;i++)
                {
                    //add in the parameter to the insert command
                    insertionCommand.CommandText += "@val" + i.ToString() + ",";
                //add the parameter
                    insertionCommand.Parameters.AddWithValue("@val"+i.ToString(), values[i]);
                }
                //remove the last comma from the insert command and add a bracket
                insertionCommand.CommandText = insertionCommand.CommandText.Substring(0, insertionCommand.CommandText.Length - 1);
                insertionCommand.CommandText+=")";

                insertionCommand.ExecuteNonQuery();
            }
        }
    }

    //this is the dummy function to show how to populate the list to pass as the values
    public void UseInsert()
    {
        List<string> insertValues = new List<string> { };
        insertValues.Add("Bruce");
        insertValues.Add("Wayne");

        InsertToDatabase("people", "Name,Surname", insertValues);
    }