Reputation: 31
I am new to Cassandra and trying to write a program in C# for insertion and deletion. I want to know if there is a way i can use variables instead of values in the insert command ? When i try the following:
string s1="A";
string s2="B";
session.Execute("insert into users (lastname, firstname) values (s1,s2)");
The error occurs: A first chance exception of type 'Cassandra.SyntaxError' occurred in Cassandra.dll
Upvotes: 2
Views: 1517
Reputation: 57798
Assuming that you are using the DataStax CQL3 C# Driver, the best way to go about this is to use a prepared statement. Once you set that up, you bind your variables and Execute
, like this:
string strCQL = "INSERT INTO users (lastname, firstname) VALUES (?,?)";
string s1 = "A";
string s2 = "B";
PreparedStatement preparedStatement = session.Prepare(strCQL);
BoundStatement boundStatement = preparedStatement.Bind(s1,s2);
session.Execute(boundStatement);
Please don't ever build a CQL statement with string.Format (or string concatenation) and execute it. Cassandra/CQL can also be subject to injection-based attacks, so you should always use a prepared statement and bind your variables to it. Also, if you have a statement that you are going to run multiple times (ex: within a loop), you can get better performance by preparing it prior to the loop, and binding/executing within.
Upvotes: 5