Passing parameter to Cassandra CQL query using DataStax client - java

I am using datastax as a client for connecting to cassandra. I have successfully connected to cassandra cluster/keyspace/column families through Java. I am trying, firing some queries on cassandra column family thriugh java. For me it is working for simple queries like
ResultSet results = session.execute("select * from demodb.customer where id = 1");
Now I want to take id parameter from user and pass it to session.execute(); statement.
How should I go about it?

Here is a code example of inserting data about an image using a prepared statements.
PreparedStatement statement = getSession().prepare(
"INSERT INTO pixelstore.image " +
"(image_name, " +
" upload_time, " +
" upload_by, " +
" file_type, " +
" file_size" +
") VALUES (?, ?, ?, ?, ?);");
// create the bound statement and initialise it with your prepared statement
BoundStatement boundStatement = new BoundStatement(statement);
session.execute( // this is where the query is executed
boundStatement.bind( // here you are binding the 'boundStatement'
"background", TimeUtil.getTimeUUID(), "lyubent", "png", "130527"));
There have been two recent blog posts on planet cassandra with a demo of what the driver can do, they contain code examples so check them out:
Materialized View with Cassandra and DataStax Java Driver
Small Java Application using DataStax Java Driver and Cassandra 1.2 working

You need to create a prepared statement. Then you need to bind that statement with the ID value you got from the user. Then you can execute the bound statement.

Related

Deadlock in SQLServer using Java + JDBC, but not when executing same commands in SSMS [duplicate]

I have a java servlet application and I'm using a prepared query to update a record in a SQL Server Database table.
Lets say I want to execute UPDATE MyTable SET name = 'test' WHERE id = '10'. (Yes, id is a varchar)
I used the following code to make this happen:
PreparedStatement pstmt = con.prepareStatement("UPDATE MyTable SET name = ? WHERE id = ?");
pstmt.setString(1, getName() );
pstmt.setString(2, getID() );
pstmt.executeUpdate();
I found out that while I was running a JMeter script to simulate 2 users, this statement causes a deadlock in my database.
I wanted to check what my values were in the SQL Profiler so I used the following code, so I could check the values.
String query = String.format("UPDATE MyTable SET name = '%s' WHERE id = '%s' ", getName(), getID() );
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.executeUpdate();
Suddenly my deadlock was gone! It's a shame the last approach is vulnerable to SQL injection.
Is there somebody who can tell me what is going on and/or how to fix it?
Ok I finally found the problem and solution to my problem.
It seemed that the combination of the jTDS JDBC driver with MSSQL was the 'problem'.
This article explained my situation exactly. And with the help of this FAQ I was able to set the datasource to the right configuration.
From what I understand:
If you have statement that uses a String-like index (Like in my situation), the table performs an index SCAN instead of an index SEEK. This causes the whole table to be locked and vulnerable to deadlocks.
I hope this will help other people too.

JDBC - NetBeans x MySQL

I'm trying to create a Java Application in NetBeans which allows the user to use most MySQL RDBMS functionalities through a GUI. I have successfully written the code for the following :
Creating a Database
Dropping a Database
Creating a Table giving options for table name, no. of columns, data type for every column
I'm stuck at the part where the user gets to insert a record in the table that was just created. I'm unable to figure out how the "insert into table values ..." query can be dynamically created and passed depending on the table the user wants to enter this record in. The table could have any number of columns, of course.
I dont know if this is the correct method, but when I faced this same problem in the past, this is how I solved it :
I ran this query to find the number of columns in the table
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_catalog = 'database_name' AND table_name = 'table_name'
Then created a dynamic sql query based on no of columns:
String sql = "Insert into tablename values(";
for(int i = 1;i<=columns;i++){
sql += "?";
if (i < columns) {
sql += ", ";
}
}
sql+=");";
Then fired a Prepared Statement
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
If you also don't know the constraints and datatype of the columns, try parsing
desc tablename
I know this must be the shittiest workaround, but it worked for me;)

Java and MYSQL Syntax Issue

I'm trying to insert data into my MYSQL databse. I want to insert an int into the database which I have no problem doing. However, I want to INSERT INTO (VALUES) WHERE. I get a MYSQL syntax error when I try this.
I can INSERT and SELECT WHERE as long as they are in two seperate statements. Here is my code:
String query = ("INSERT INTO `accounts` (inventory) " + "VALUES ('"
+ Inventory.inventory + "') WHERE username='" + Frame.username
+ "' and password = '" + Frame.password + "'");
Basically, an INSERT statement can not have a WHERE clause. I am thinking that you want to UPDATE a certain record, eg
UPDATE accounts
SET inventory = 'valueHere'
WHERE userName = 'userHEre' AND password = 'passHere'
The only time an INSERT statement can have a WHERE clause is when you are inserting records from the result of a SELECT statement, eg
INSERT INTO tableName (col1, ..., colN)
SELECT col1, ..., colN
FROM table2
// WHERE ..your conditions here..
As a sidenote, your current coding style is vulnerable with SQL Injection. Consider using PreparedStatement.
Basic example of a PreparedStatement
String updateString = "UPDATE accounts SET inventory = ? WHERE userName = ? AND password = ?";
PreparedStatement updateStmt = con.prepareStatement(updateString);
updateStmt.setString(1, Inventory.inventory);
updateStmt.setString(2, Frame.username);
updateStmt.setString(3, Frame.password);
updateStmt.executeUpdate();
JDBC PreparedStatement
MySQL INSERT Syntax does not support the WHERE clause so that's why you have a syntax issue. Maybe you're looking for an UPDATE :
UPDATE [LOW_PRIORITY] [IGNORE] tbl_name
SET col_name1=expr1 [, col_name2=expr2 ...]
[WHERE where_definition]
[ORDER BY ...]
[LIMIT row_count]
Not a direct answer but more of a best practice....
You should avoid doing this type of string concatenation for any sql. You vulnerable to sql injection and it does not scale well. Instead you should look at using JdbcTemplates or NamedJdbcTemplate using the opensource spring framework.
The WHERE is not applicable in INSERT INTO Syntax. You want insert a new row in the table, and you should add the username and password as well as Inventory.inventory in VALUES set.

java sql syntax error insert into

I have problems running this sql statement. It works fine if I run it in mysql but in java I get this error:
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '' at line 1
The database has an id(pk) autogenerated, varchar, int, varchar;
Can someone help me?
int i = statement.executeUpdate("INSERT INTO sala values('','"+ nume.getText() + "', "+ Integer.parseInt(capacitate.getText())+ ", '" + sunet.getText()+"'");
Don't just try to fix this code by tweaking the SQL as per adarshr's answer. You have a fundamental security problem here which you should fix right now. You're open to SQL injection attacks due to including user data directly in your SQL.
You should use a PreparedStatement, with the parameters declared as placeholders in the SQL, but then given values separately. Exactly how you'll do that will depend on your JDBC provider, but it'll look something like this:
// TODO: Fix the column names, and close the statement in a try/finally block
PreparedStatement pst = conn.prepareStatement(
"INSERT INTO sala (nume, capacitate, sunet) VALUES (?, ?, ?)");
pst.setString(1, nume.getText());
pst.setInt(2, Integer.parseInt(capacitate.getText()));
pst.setString(3, sunet.getText());
pst.executeUpdate();
Note that if you can get capacite in a way which doesn't require integer parsing, that would be good. Otherwise, consider using NumberFormat which is more locale-friendly. Also note that I've added the column names into the SQL to make this more robust in the face of schema changes.
You haven't closed your query.
int i = statement.executeUpdate("INSERT INTO sala values('','"+ nume.getText() + "', "+ Integer.parseInt(capacitate.getText())+ ", '" + sunet.getText()+"')");
^
But more than all this, you must use PreparedStatement as Jon suggested below.

Using info from a database as variable values

I am working on a java project and I need to pull some values out of a database and turn them into variables the program will then use to make a billing statement. I can get the program to connect to the database just fine, and the mySQL statement to call the data I need is easy enough. I just can't seem to figure out how to then have it put each field returned in the resultset into a separate variable.
Shamelessly lifted from the jdbc tutorial
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(
"SELECT COF_NAME, PRICE FROM COFFEES");
while (srs.next()) {
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}
You should review the JDBC tutorial, and this section answers your question.

Categories

Resources