2

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

Nilay
  • 31
  • 2

2 Answers2

5

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.

Community
  • 1
  • 1
Aaron
  • 55,518
  • 11
  • 116
  • 132
0

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

knifewine
  • 46
  • 2