Hello all,
I am new to Rethink-db can anyone help me with this as i mentioned in above query.
I am creating one java service with Rethink-db so whenever new entries inserted into Rethink-db a java method should call by Rethink-db itself with data that i inserted. And is this possible to achieve it? Thanks.
I hope you have proper dependency set, below code may help you.
static Connection con = r.connection().hostname("localhost").port(28015).db("db_name").connect();
public static final RethinkDB r = RethinkDB.r;
public static void getChangeEffect() {
Result<Object> changes = r.table("table_name").changes().run(con);
for (Object change : changes) {
System.out.println(change);
}
}
The above code will execute and prints all the rows whenever a new insertion takes place.
This should have at least 3 entries in the array when I view it at a later stage, but it only displays one. I believe this is thee problematic method, any advice?
String[] getKidsNamebyCid(int cid) {
String[] out = new String[20];
try {
String qry = "SELECT KIDSNAME FROM TBLKIDS WHERE CID = ?";//setting query command
ps = connect.prepareStatement(qry);//preparing statement
ps.setInt(1, cid);//setting CID
ps.executeQuery();//running command
int i = 0;
while (ps.getResultSet().next()) {
out[i] = ps.getResultSet().getString("KIDSNAME");
i++;
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return out;
}
The getResultSet() call isn't a getter. That method does things to the DB, and you can't just repeatedly call it; the first time you get a ResultSet object (which you need to close), the second time everything is reset. So don't; you need to call getResultSet() once.
How do I know? By reading. Straight from getResultSet() documentation:
This method should be called only once per result.
Also this code is littered with severe code issues more generally focussed around resources. Resources are objects which aren't -just- a bunch of bits in memory, they represent (and hold open) a 'resource'. In the case of DBs, it's connections to the DB engine. You can't just make resources, you have to always put them in 'guarding' blocks that guarantee the resources are cleaned up. As a consequence, you never want them to be a field unless there's no other way (and then the thing they are a field inside of becomes a resource).
So, the fact that your PreparedStatement is a field? No good. The fact that you call .getResource just like that, unguarded? No good.
Finally, your exception handling is silly. The default act when facing checked exceptions is to just add them to your throws clause. If you can't do that, the right move is throw new RuntimeException("uncaught", e);, not what you did.
executeQuery already returns a resultset. Generally, never call getResultSet*.
Finally, arrays are more or less obsolete; you want collections.
Putting it all together:
// delete your 'ps' field!
List<String> getKidsNamebyCid(int cid) throws SQLException {
var out = new ArrayList<String>();
String qry = "SELECT KIDSNAME FROM TBLKIDS WHERE CID = ?";
try (PreparedStatement ps = connect.prepareStatement(qry)) {
ps.setInt(1, cid);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) out.add(rs.getString("KIDSNAME"));
}
}
return out;
}
*) The PreparedStatement API is extremely unfortunate. The way you interact with a PS is wildly different vs. a Statement (which you should rarely use; you can't add user input to a plain jane Statement), and yet because reasons and history PreparedStatement extends Statement. That means a whole bevy of methods are in PreparedStatements that you should never call. That's unfortunate. There are 2 things to learn here: [1] Java does not break backwards compatibility, even if that means some of the APIs are horrible, and [2] JDBC is not really meant for 'human consumption'. We don't program our CPUs in machine code either, yet machine code exists and will continue to. We use 'machine code' as glue; something library and language developers use as common tongue. So it is with JDBC: It's not meant for you. Use a library with a nice API, like JDBI. This probably goes beyond what your high school curriculum wants, but hey. There's not much to say except: It's on your curriculum and teacher that they're making you work with outmoded tools 'real'** developers don't use.
**) 'real' in the sense of: Is writing code that powers apps that get a lot of dollars and/or eyeballs.
You need to learn how PreparedStatement actually works. I highly recommend you follow a tutorial to learn how to use it, then follow the pattern for your own code.
But it's also all in the documentation, so let be quote the various relevant pieces.
The javadoc of executeQuery() says:
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
The code in the question is already wrong at this point, since it **ignores the return value of the executeQuery() call.
In addition, the javadoc of getResultSet() says:
Retrieves the current result as a ResultSet object. This method should be called only once per result.
The code in the question is even more wrong at this point, since it calls getResultSet() repeatedly in a loop.
If you had read the javadoc of the methods you're using, it would have been obvious that something is wrong. As already stated, going through a tutorial would have shown how to do this right. Actually, any web search for examples of executing a query using JDBC would show that.
For extra background information for how it works, the javadoc of execute() says:
Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement. Some prepared statements return multiple results; the execute method handles these complex statements as well as the simpler form of statements handled by the methods executeQuery and executeUpdate.
The execute method returns a boolean to indicate the form of the first result. You must call either the method getResultSet or getUpdateCount to retrieve the result; you must call getMoreResults to move to any subsequent result(s).
The javadoc of getMoreResults() says:
Moves to this Statement object's next result, returns true if it is a ResultSet object, and implicitly closes any current ResultSet object(s) obtained with the method getResultSet.
The "return multiple results" is not talking about multiple rows from a single query, but about multiple results from multiple queries. It generally requires the execution of a stored procedure, or a block of SQL code, for this to happen.
This is how to correctly get the multiple rows from the execution of a single SELECT statement:
String qry = "SELECT KIDSNAME FROM TBLKIDS WHERE CID = ?";
try (PreparedStatement ps = connect.prepareStatement(qry)) {
ps.setInt(1, cid);//setting CID
try (ResultSet rs = ps.executeQuery()) {
int i = 0;
while (rs.next()) {
out[i] = rs.getString("KIDSNAME");
i++;
}
}
}
If the SQL code in question had returned multiple result sets, you would do it this way:
try (PreparedStatement ps = connect.prepareStatement(qry)) {
// call ps.setXxx() methods here
boolean isResultSet = ps.execute();
while (isResultSet) {
try (ResultSet rs = ps.getResultSet()) {
int i = 0;
while (rs.next()) {
// call rs.getXxx() methods here
i++;
}
}
isResultSet = ps.getMoreResults();
}
}
That is better written using for loops, to keep the loop logic together:
try (PreparedStatement ps = connect.prepareStatement(qry)) {
// call ps.setXxx() methods here
for (boolean isResultSet = ps.execute(); isResultSet; isResultSet = ps.getMoreResults()) {
try (ResultSet rs = ps.getResultSet()) {
for (int i = 0; rs.next(); i++) {
// call rs.getXxx() methods here
}
}
}
}
Im currently working on a simple program to show the contents of a database. Im not sure how to get two of the textbox values to multiply together and put the result in the third. THis is the section of code:
private void GetProductTable() {
ResultSet rs = GetProducts();
try {
jTable2.setModel(buildTableModel(rs));
} catch (Exception ex) {
}
jTable2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JTable target;
target = (JTable) e.getSource();
int row;
row = target.getSelectedRow();
String[] result;
result = getRowAt(target, row);
ProductID.setText(result[0]);
ProductName.setText(result[1]);
ProductSupplierID.setText(result[2]);
ProductCataID.setText(result[3]);
ProductInStock.setText(result[4]);
ProductOnOrder.setText(result[5]);
ProductReorderLvl.setText(result[6]);
ProductDiscon.setText(result[7]);
ProductUnitPrice.setText(result[8]);
ProductUnitPrice1.setText();
}
});
}
I need result[5] to multiply by result[8] and put the total in ProductUnitPrice1. The results are being retrieved from an external database. I have tried a few things and i just cant get it to work, all I keep getting is the contents or result 5 and 8 both put into the box. I know I need to get it to look at the results as a integer and not a string but everything I have tried has not worked.
This may be a really simple solution but I am very much a beginner and I need this to work in order to pass the Java unit in my HND.
Any help will be much appreciated.
int result=Integer.valueOf(result[5])*Integer.valueOf(result[8]);
ProductUnitPrice1.setText(result);
you might need to change datatypes to doubles. maybe this works too:
ProductUnitPrice1.setText(String.valueOf(Integer.valueOf(result[5])*Integer.valueOf(result[8])));
I am trying to store the output value of one method in a global variable so that i can use that value in another method. I code in java with play framework.
I have method where i need to run a query and the query is a dynamic one it is generated based on the filter conditions from user request.
I wish to save the resultSet in the first method so that i can use that resultSet data in the next method.
resultSet queryData;
public String list() {
connection = "";
resultSet data;
query ="";
data = this.Execute(query,connection);
return "data";
}
public byte[] dataList() {
connection = "";
while(queryData.next()){
xyz;
}
}
This is a sample of my code i have similar to this.
In my first method the query is executed and the resultSet is assigned to variable data.
I would like to store it in queryData global variable and use that in the next method.
Is there a way to do so?
Pls help
If your local variable data in list method is returned, then I don't understand why you need global variable to store it? You can call it in your next method, and store it in a local variable there??
For example:
public ResultSet list() {
connection = "";
ResultSet data;
query ="";
data = this.Execute(query,connection);
return data;
}
public byte[] dataList() {
ResultSet data = list();
connection = "";
while(data.next()){
xyz;
}
}
I have created web service in JAVA Netbeans and called MySQL data through rest web service.
Edited code:
For loop shows all areas in sorting order then why as json output all data are not displayed in ascending order???
my method is as follows :
#GET
#Path("/ShowAreasDup")
#Produces(MediaType.APPLICATION_JSON)
public List<EntityAreas> ShowAreasDup(){
ArrayList<EntityAreas> listSort;
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASSWORD);
String query = "SELECT * FROM Areas ORDER BY AreaName";
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery(query);
// iterate through the java resultset
while (resultset.next())
{
int id = resultset.getInt("AreaID");
String restroName = resultset.getString("AreaName");
EntityAreas anames=new EntityAreas();
anames.setAreaid(id);
anames.setAreaname(restroName);
ShowentityAreas.put(id, anames);
}
statement.close();
}
catch(HeadlessException | SQLException |ClassNotFoundException ee)
{
JOptionPane.showMessageDialog(null, ee);
}
listSort=new ArrayList<EntityAreas>(ShowentityAreas.values());
Collections.sort(listSort,new Comparator<EntityAreas>(){
#Override
public int compare(EntityAreas o1, EntityAreas o2) {
return o1.getAreaname().compareTo(o2.getAreaname());
}
});
for(EntityAreas entityarea:listSort){
System.out.println(entityarea);
}
return listSort;
}
thank you in advance for help
Edit :
Above code is works perfectly for me
thanks to all for giving me a direction to the answser :)
Given your code, there could be some hypothesis. The most probable is that ShowAreas stores the information in an non ordered data structure (for example an HashMap).
If you want to maintain your values in order , you have to use some additional data structure. For example, you can use a TreeSet for the values.
Another solution could be to sort the values immediatly before returning them (javadoc),
// Get the elements
List<Areas> areas = new ArrayList<Areas>(ShowAreas.values());
// Sort them
Collections.sort(areas);
// Return them
return areas;
Pay attention: if you want to use this method, the class Areas must implement Comparable.
A last advise: don't put the code that interacts with the database in the class that has the responsibility to receive external REST calls. You violates the single responsibility principle and your application will become unmaintainable very quickly. Try to use a structure Controller - Service - Repository.