Nilay
Nilay

Reputation: 31

Using variables while inserting in Cassandra

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

Answers (2)

Aaron
Aaron

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

knifewine
knifewine

Reputation: 46

You need String.format or better yet use prepared statements.

http://www.datastax.com/documentation/developer/csharp-driver/2.1/csharp-driver/reference/21features/namedParameters.html

Upvotes: 0

Related Questions