How to insert JSON into cassandra database using java API? - java

This is the code I have used for writing my program but there are errors - please give us some suggestions with the corrected code.
session.execute("INSERT INTO users JSON '{'id':'user123' , 'age':21 ,'state':'TX'}';");
The errors are directed to this one statement so I thought that its not necessary to present the whole code here.TABLE users has already been created in the cassandra database with the columns id, age and state. I could not find any proper answers for this problem anywhere, I hope my problem is solved here.

Here is the working query and below java code where I insert it and the results
"INSERT INTO users JSON '{\"id\":888 , \"age\":21 ,\"state\":\"TX\"}'";
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
public class CasandarConnect {
public static void main(String[] args) {
String serverIP = "127.0.0.1";
String keyspace = "mykeyspace";
Cluster cluster = Cluster.builder()
.addContactPoints(serverIP)
.build();
Session session = cluster.connect(keyspace);
String cqlStatement = "INSERT INTO users JSON '{\"id\":888 , \"age\":21 ,\"state\":\"TX\"}'";
session.execute(cqlStatement);
}
}
Result
cqlsh:mykeyspace> select * from users;
id | age | state
------+-----+-------
1745 | 12 | smith
123 | 21 | TX
888 | 21 | TX

Related

Insert a row in a table with referencing to a value from other table

I have 2 tables, subject and student respectively
id | name
----+-----------------------------
1 | Math
id | student_name | score | subject_id
----+--------------+-------+------------
11 | Mark | 78.5 | 2
I have the Java code
public boolean insertStudent(String student_name,float score,String name) {
boolean res=false;
try(PreparedStatement statement=this.c.prepareStatement(INSERT_STU);){
statement.setString(1,student_name);
statement.setFloat(2,score);
statement.setString(3,name);
res=statement.execute();
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
return res;
}
I have the query string for INSERT_STU
private static final String INSERT_STU="INSERT INTO student(student_name,score,subject_id) VALUES(?,?,(SELECT id from subject where name=?))";
This works in postgres. But is there any other way to do it?
*It has to be passed with subject name (String name) and not subject id. Since I won't be knowing the subject_id, I pass the name.
you can change your query to this which probably is more readable :
INSERT INTO student (student_name,score,subject_id)
SELECT ?,?,id from subject where name = ?
but be careful here , if we can't find any match in subject table for given name , nothing will be inserted.

Execute multiple queries in java using MySQL JDBC [duplicate]

Hi I was wondering if it is possible to execute something like this using JDBC as it currently provides an exception even though it is possible in the MySQL query browser.
"SELECT FROM * TABLE;INSERT INTO TABLE;"
While I do realize that it is possible with having the SQL query string being split and the statement executed twice but I was wondering if there is a one time approach for this.
String url = "jdbc:mysql://localhost:3306/";
String dbName = "databaseinjection";
String driver = "com.mysql.jdbc.Driver";
String sqlUsername = "root";
String sqlPassword = "abc";
Class.forName(driver).newInstance();
connection = DriverManager.getConnection(url+dbName, sqlUsername, sqlPassword);
I was wondering if it is possible to execute something like this using JDBC.
"SELECT FROM * TABLE;INSERT INTO TABLE;"
Yes it is possible. There are two ways, as far as I know. They are
By setting database connection property to allow multiple queries,
separated by a semi-colon by default.
By calling a stored procedure that returns cursors implicit.
Following examples demonstrate the above two possibilities.
Example 1: ( To allow multiple queries ):
While sending a connection request, you need to append a connection property allowMultiQueries=true to the database url. This is additional connection property to those if already exists some, like autoReConnect=true, etc.. Acceptable values for allowMultiQueries property are true, false, yes, and no. Any other value is rejected at runtime with an SQLException.
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
Unless such instruction is passed, an SQLException is thrown.
You have to use execute( String sql ) or its other variants to fetch results of the query execution.
boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );
To iterate through and process results you require following steps:
READING_QUERY_RESULTS: // label
while ( hasMoreResultSets || stmt.getUpdateCount() != -1 ) {
if ( hasMoreResultSets ) {
Resultset rs = stmt.getResultSet();
// handle your rs here
} // if has rs
else { // if ddl/dml/...
int queryResult = stmt.getUpdateCount();
if ( queryResult == -1 ) { // no more queries processed
break READING_QUERY_RESULTS;
} // no more queries processed
// handle success, failure, generated keys, etc here
} // if ddl/dml/...
// check to continue in the loop
hasMoreResultSets = stmt.getMoreResults();
} // while results
Example 2: Steps to follow:
Create a procedure with one or more select, and DML queries.
Call it from java using CallableStatement.
You can capture multiple ResultSets executed in procedure.
DML results can't be captured but can issue another select
to find how the rows are affected in the table.
Sample table and procedure:
mysql> create table tbl_mq( i int not null auto_increment, name varchar(10), primary key (i) );
Query OK, 0 rows affected (0.16 sec)
mysql> delimiter //
mysql> create procedure multi_query()
-> begin
-> select count(*) as name_count from tbl_mq;
-> insert into tbl_mq( names ) values ( 'ravi' );
-> select last_insert_id();
-> select * from tbl_mq;
-> end;
-> //
Query OK, 0 rows affected (0.02 sec)
mysql> delimiter ;
mysql> call multi_query();
+------------+
| name_count |
+------------+
| 0 |
+------------+
1 row in set (0.00 sec)
+------------------+
| last_insert_id() |
+------------------+
| 3 |
+------------------+
1 row in set (0.00 sec)
+---+------+
| i | name |
+---+------+
| 1 | ravi |
+---+------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Call Procedure from Java:
CallableStatement cstmt = con.prepareCall( "call multi_query()" );
boolean hasMoreResultSets = cstmt.execute();
READING_QUERY_RESULTS:
while ( hasMoreResultSets ) {
Resultset rs = stmt.getResultSet();
// handle your rs here
} // while has more rs
You can use Batch update but queries must be action(i.e. insert,update and delete) queries
Statement s = c.createStatement();
String s1 = "update emp set name='abc' where salary=984";
String s2 = "insert into emp values ('Osama',1420)";
s.addBatch(s1);
s.addBatch(s2);
s.executeBatch();
Hint: If you have more than one connection property then separate them with:
&
To give you somthing like:
url="jdbc:mysql://localhost/glyndwr?autoReconnect=true&allowMultiQueries=true"
I hope this helps some one.
Regards,
Glyn
Based on my testing, the correct flag is "allowMultiQueries=true"
Why dont you try and write a Stored Procedure for this?
You can get the Result Set out and in the same Stored Procedure you can Insert what you want.
The only thing is you might not get the newly inserted rows in the Result Set if you Insert after the Select.
I think this is the easiest way for multy selection/update/insert/delete. You can run as many update/insert/delete as u want after select (you have to make a select first(a dummy if needed)) with executeUpdate(str) (just use new int(count1,count2,...)) and if u need a new selection close 'statement' and 'connection' and make new for next select. Like example:
String str1 = "select * from users";
String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement(str1);
ResultSet theResult = theStatement.executeQuery();
int count8 = theStatement.executeUpdate(str9);
theStatement.close();
theConnection.close();
theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement(str2);
theResult = theStatement.executeQuery();
ArrayList<Port> portList = new ArrayList<Port>();
while (theResult.next()) {
Port port = new Port();
port.setPort_id(theResult.getInt("port_id"));
portList.add(port);
}
I hope it helps

Jena - Access elements in model from a QuerySolution and update them

I want to perform simple operations using one test model I created using Protégé 5. In my case I have a user defined this way in my owl file:
<owl:NamedIndividual rdf:about="&user-test-2;u01">
<rdf:type rdf:resource="&user-test-2;user"/>
<user-test-2:email rdf:datatype="&xsd;string">email1#test.net</user-test-2:email>
<user-test-2:hasGender rdf:resource="&user-test-2;male"/>
<user-test-2:isYearsOld rdf:resource="&user-test-2;18-24"/>
</owl:NamedIndividual>
I have been able to load the model correctly and perform a basic search using SPARQL to get male users and related properties, obtaining the following results:
String fileName = "user-test-2.owl";
Model model = RDFDataMgr.loadModel(fileName);
final String ns = "http://www.semanticweb.org/ontologies/user-test-2#";
String queryString = "PREFIX test: <http://www.semanticweb.org/ontologies/user-test-2#> "
+ "SELECT ?subject "
+ "WHERE { ?subject test:hasGender test:male } ";
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out, results, query);
------------
| subject |
============
| test:u01 |
-----------
Now I would like to access the properties of the owl:NamedIndividual and update one of them. For instance, to change the user's email.
EDIT
I have been able to access the properties using this code:
Property emailDp = model.getProperty(ns + "email");
Property isYearsOld = model.getProperty(ns + "isYearsOld");
for ( ; results.hasNext() ; ) {
QuerySolution soln = results.nextSolution() ;
Resource res = soln.getResource("subject");
Resource user = model.getResource( res.getURI());
System.out.println(user.getProperty(emailDp));
System.out.println(user.getProperty(isYearsOld));
}
Now I would need to update one of them.
For the moment I have not found any useful example to perform these kind of things so any help is welcome.
Thanks in advance.
So you want to update the property emailDp or isYearsOld of a given user.
Assuming a user only has one e-mail address and/or one age, we can get the property directly by calling:
Statement emailStatement = user.getProperty(emailDp);
Statement ageStatement = user.getProperty(isYearsOld);
The age or email of a user can then be retrieven using:
Resource email = (Resource) emailStatement.getObject();
Resource age = (Resource) ageStatement.getObject();
Updating either one of these can easily be done by:
user.removeProperty(emailDp, email);
user.removeProperty(isYearsOld, age);
user.addProperty(emailDp, newEmail);
user.addProperty(isYearsOld, newAge);
If a user has MORE THAN ONE of either, you will have to device if the new e-mail address replaces all old ones with user.removeAll(emailDp) or iterating over the list as you are doing and performing any kind of check, and delete the one you want, similar to above examples.

Select a specific value in Access using SQL

I am working on a project that links Access to a Java GUI. I am currently looking for a way to select a record, in a query, that contains a specific value.
If my fields are:
Name | Job | Hours Worked
Tom | Sales Support | 6
Bill | Manager | 8
Tom | Sales Floor | 5
and I enter Tom in a search field in the GUI, I would like it to return the following to the GUI:
Name | Job | Hours Worked
Tom | Sales Support | 6
Tom | Sales Floor | 5
I tried using this code:
ArrayList<String> list = new ArrayList<>();
String filePath = "C:\\Users\\Bob\\Schedule.accdb";
Connection con=DriverManager.getConnection("jdbc:ucanaccess://"+filePath);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM [Double Booking] WHERE [Name] = Tom");
while(rs.next()) list.add(rs.getString(1));
con.close();
return list.toArray();
but I get the error:
net.ucanaccess.jdbc.UcanaccessSQLException: user lacks privilege or object not found: TOM
When I enter st.executeQuery("SELECT [Name] FROM [Double Booking]") I get a similar error:
net.ucanaccess.jdbc.UcanaccessSQLException: user lacks privilege or object not found: DOUBLE BOOKING
Since Tom is intended to be a string literal, you need to add quote characters:
"SELECT * FROM [Double Booking] WHERE [Name] = 'Tom'"
That said, if 'Tom' is just an example, it would be better to use a parameterised query if possible.

Testing a method to return unique values from a result set of a db query

Let's say there is a database table named "Students".
Students Table
|---------------|---------------|
| Name | Age |
|---------------|---------------|
| John | 9 |
|---------------|---------------|
| Jane | 7 |
|---------------|---------------|
| Dana | 8 |
|---------------|---------------|
| John | 6 |
|---------------|---------------|
I make a request to the database to return all names using:
SELECT Name FROM Students
So the result set would be:
ResultSet rs = {"John" "Jane" "Dana" "John"}
I then want to return all unique values so I write a method called populateSet() to populate a HashSet setOfNames with rs.
After executing populateSet(ResultSet rs), only unique names appear:
"John" "Jane" "Dana"
Here is the validation test:
public void testValidation() {
// Skipping the test data / db connection / query part
ResultSet rs = ResultSet received back from DB
Set<String> expected = {"John", "Jane", "Dana"};
Set<String> actual = WhateverClass.populateSet(rs);
assertEquals(expected, actual);
}
What are some of the possible unit tests that I could write?
I know I should write a null, empty, and negative tests. What are some corner cases?
Potential corner cases:
Very large table (millions of rows)
Transactionality - e.g, what happens if a name is inserted/deleted/updated after you start the table scan?
Data ordering
Case sensitivity/insensitivity of names
non-ASCII characters in names

Categories

Resources