What is the best way to handle Java ResultSet? I'm creating a Desktop application that will connect to an oracle database using JDBC.
However, I am having problem with handling ResultSets since I can't do comparison using for loop.
// create a database connection object
DB db = new DB();
// get rows of my first table and second table
ResultSet firstRS = db.getMyFirstTable();
ResultSet seconRS = db.getSecondTable();
// compare the two tables
while(firstRS.next())
{
// get the row of my first table
String firstRSRow = firstRS.getString("col1");
while(secondRS.next())
{
// get the row of my second table
String secondRSRow = seconRS.getString("col1");
// compare row from first table to the row in second table
if(firstRSRow.startsWith(secondRSRow))
{
// do some processing here....
} // end if
} // end while
} // end while
I know that this could be accomplish with Hibernate with a few lines of code but I don't have the luxury of time to study it.
I also found commons DbUtils from apache but it seems complicated for me as a novice programmer.
Is there other way/tools/libraries/framework simple enough to get ResultSet from databases and manipulate it in simple and straightforward manner?
I will also appreciate if you could direct me to a website that has sample codes concerning java database connectivity.
Thank you very much for your support.
Why ResultSet? You could easily compare values with SELECT statement. In case you still want to ResultSet then think about CachedRowSet.
DB db = new DB();
// get rows of my first table and second table
ResultSet firstRS = db.getMyFirstTable();
ResultSet seconRS = db.getSecondTable();
// compare the two tables
while(firstRS.next() || secondRS.next())
{
// get the row of my first table
String firstRSRow = firstRS.getString("col1");
String secondRSRow = seconRS.getString("col1")
// compare row from first table to the row in second table
if(firstRSRow.startsWith(secondRSRow))
{
// do some processing here....
} // end if
} // end while
public static boolean resultset(String SQL1, String SQL2){
public boolean status=false;
ResultSet ViewResultset = st.executeQuery(SQL1);
ResultSet QueryResultset = st.executeQuery(SQL2);
while (QueryResultset.next() | ViewResultset.next())
if (ViewResultset.getRow() == 0 | QueryResultset.getRow() == 0) {
break;
} else {
for (int i = 1; i < ViewResultset.getMetaData().getColumnCount() + 1; i++) {
System.out.println("OOO"+ QueryResultset.getMetaData().getColumnCount());
String columnName = ViewResultset.getMetaData().getColumnName(i);
System.out.println("ColumnName :" + columnName);
for (int j = 1; j < QueryResultset.getMetaData().getColumnCount() + 1; j++)
if (ViewResultset.getMetaData().getColumnName(i).equals(QueryResultset.getMetaData().getColumnName(j))&& !(QueryResultset.getString(columnName) == null || ViewResultset.getString(columnName) == null))
if (ViewResultset.getString(columnName).toUpperCase().contains(QueryResultset.getString(columnName).toUpperCase())) {
System.out.println(" Actual "+ ViewResultset.getMetaData().getColumnName(i) + " Expected: "+ ViewResultset.getString(columnName));
status=true;
}
else {System.out.println(" Actual "+ ViewResultset.getMetaData().getColumnName(i) + " Expected: "+ ViewResultset.getString(columnName));
}
}
}
return status;
}
}
ResultSet is a subclass of Object ultimately and we can compare two or more objects directly. A little specific to your question:
ResultSet rs=st.executeQuery(sql1);
ResultSet rs1=st.executeQuery(sql2);
where sql1 and sql2 are 2 Statements
while(rs.next() && rs1.next()){
int a=rs.next();
int b=rs1.next();
if(a==b){
System.out.println("Compairing two ResultSets");
}
}
Related
I want compare to the data sent with all data in the db. this coce compare the date insert only with the last row. how can I compare with all row in the db?
................................................................................................
String sData= request.getParameter("idatadata");
String sAzienda= request.getParameter("idazienda");
String sCommessa= request.getParameter("idcommessa");
String date = "";
String company = "";
String order = "";
Connect con = new Connect();
try {
Connection connection = con.createConnection();
Statement statement = connection.createStatement();
String sql ="SELECT * FROM table";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()) {
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
}
if((sData.equals(date) && sAzienda.equals(company)) && sCommessa.equals(order)) {
out.print("already sent");
con.closeConnection(connection);
}
else {
DbConnect.insertInDb(connection, sData, sOre, sMinuti, sAzienda, sCommessa, sRifInterno);
dbc.closeConnection(connection);
response.getWriter().append("ok! ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
The reason why you are checking only the last row, is that your while loop keeps overwriting your local variables each time you retrieve a row:
while(resultSet.next()) {
// these lines overwrite the local vars for each row
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
}
But you don't actually check the local vars inside the loop before moving on to the next row from the db. You should add the check into the loop:
while(resultSet.next()) {
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
// add your check here
if((sData.equals(date) && sAzienda.equals(company)) && sCommessa.equals(order)) {
out.print("already sent");
break;
}
}
Preferably, just perform a select based on the data you are looking for. If you get no results, then the data isn't in the db. This method is much more efficient. If you do decide to go down this path (which is a good idea), use a prepared statement so that you don't introduce a SQL injection vulnerability into your code.
I want to do the following:
Connect to a Postgres database and select the contents of a particular table 2 rows at a time
Take the 2 rows, convert them to CSV strings and send that string over the wire to a RESTful API endpoint
The problem I am having is that in order to process the ResultSet and convert it into a CSV String, I need to call rs.next() but in doing that, I am pulling the next 'batch' from the database. Here's the code I have so far:
public void load() throws Exception {
Connection conn = connectToDB();
conn.setAutoCommit(false);
Statement st = conn.createStatement();
st.setFetchSize(2);
ResultSet rs = st.executeQuery("SELECT * FROM friends");
String csv = resultSetToCSV(rs);
System.out.println("CSV output is: " + csv);
rs.close();
st.close();
}
private static String resultSetToCSV(ResultSet rs) throws Exception {
int colCount = rs.getMetaData().getColumnCount();
StringBuilder result = new StringBuilder();
while (rs.next()) {
for (int i = 0; i < colCount; i++) {
result.append("\"").append(rs.getString(i + 1)).append('"');
}
result.append(System.lineSeparator());
}
return result.toString();
}
How can I get this to work so that each "batch" of 2 rows is processed and converted to a CSV string? I want to do this because I am going to be running this on a very large table which won't fit into memory (I am just testing it out with a batch size of 2).
You can set the fetch size with ResultSet.setFetchSize(int) but generally you should not concern yourself with the entire table fitting in memory and let the driver do the job.
Good day to you all
I am trying to import specified tables from access db to store it in a H2 embedded db to be used locally and update changes back to server (access) whenever connection is possible.
But as code below shows i am stuck at inserting dynamically data to the newly created H2 database.
I am getting this error
org.h2.jdbc.JdbcSQLException: Column "1" not found; SQL statement:
INSERT INTO Users ( ID_USER, Nt_id, Name, Level, Psw_Admin ) VALUES ( 1 ,***** ,******* ,ALL ,***** ) [42122-181]
As you see i have used preparedstatement, and used quotes (because the columns newly created are VARCHAR all) yet none of the above solved the issue
here is my code of inserting:
while (rs.next()){
String object="";
String item="";
for (int i=1;i<=columncount;i++){
object=rs.getObject(i)+"";
if (i==1){
item="`"+item+object;
}else if (i==columncount){
item=item+"` ,`"+object+"`";
} else{
item=item+"` ,`"+object;
}
System.out.println(object);
}
PreparedStatement pst3=conn2.prepareStatement("INSERT INTO Users "+" ( "+columnnamepst3+" ) VALUES ( "+item+" )");
pst3.executeUpdate();
pst3.close();
System.out.println("Done...next row");
}
rs.close();
rs is the result set from access db
conn2 is the connection to H2
EDIT1: corrected the code quoted
Thanks in advance
So in another forum someone proposed this solution and it worked so i am posting it maybe it'll help someone else
String additif="VALUES (";
for(int i1=1;i1<=columncount;i1++){
if(i1!=columncount){
additif=additif+"?,";
}else{
additif=additif+"?)";
}
}while (rs.next()){
ArrayList<String> object=new ArrayList<String>();
for (int i1=1;i1<=columncount;i1++){
object.add(""+rs.getObject(i1));
System.out.println(object);
}
PreparedStatement pst3=conn2.prepareStatement("INSERT INTO `"+Tabledb+"` "+additif);
for(int i1=0;i1<object.size();i1++){
pst3.setString(i1+1, object.get(i1));}
pst3.executeUpdate();
pst3.close();
System.out.println("Done...next row");
}
rs.close();
conn.close();
System.out.println("Done!");
Your problem seems to be the using of backticks (`) for the string values. Use apostrophes (') instead.
while (rs.next()) {
String object="";
String item="";
for (int i=1;i<=columncount;i++) {
object=rs.getObject(i)+"";
if (i==1) {
item="'"+item+object;
} else if (i==columncount) {
item=item+"' ,'"+object+"'";
} else {
item=item+"' ,'"+object;
}
System.out.println(object);
}
PreparedStatement pst3=conn2.prepareStatement("INSERT INTO Users ( "+columnnamepst3+" ) VALUES ( "+item+" )");
pst3.executeUpdate();
pst3.close();
System.out.println("Done...next row");
}
rs.close();
EDIT
As your column names seem to be prepared beforehand, you could use PrepareStatement's parameter passing abilities:
String item="";
for (int i = 1; i <= columncount; i++) {
items += (i == 1 ? "" : ", " ) + "?";
}
PreparedStatement pst3=conn2.prepareStatement("INSERT INTO Users ( "+columnnamepst3+" ) VALUES ( "+item+" )");
while (rs.next()) {
for (int i=1;i<=columncount;i++) {
pst3.setString(i,rs.getString(i));
}
pst3.executeUpdate();
System.out.println("Done...next row");
}
pst3.close();
rs.close();
Should also add some error handling (try blocks).
I am trying to add the databases to specific column,row the column always is the same but the row change. So I enter the variable and trying to add one to the number but not luck all is printing are 0 so is not adding any number to the variable for that reason my table stay in the same row and never change. I try i++; i=i+1; all I have is 0 on the println(). Im using Netbeans.
Statement stmt = null;
String sql="select * from gateway where date= "+id;
try{
Connect conn=new Connect();
stmt = conn.makeStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
int i=0;
Object ids = rs.getString("Business");
Object items = rs.getString("GatewayJob");
Object descriptions = rs.getString("Status");
Object quantitys = rs.getString("Timework");
Object price = rs.getString("Notes");
jTable1.getModel().setValueAt(ids,i, 0 );
jTable1.getModel().setValueAt(items, i, 1);
jTable1.getModel().setValueAt(descriptions, i, 2);
jTable1.getModel().setValueAt(quantitys, i, 3);
jTable1.getModel().setValueAt(price, i, 4);
System.out.println(i);
i++;
}
In you code
while(rs.next()) {
int i=0;
move the int i = 0; to before your while loop
this statement will reset i back to 0 everytime
Don't use the setValueAt() method. This implies you have loaded the TableModel with a bunch of rows containing null values which is a bad design as you don't know how many rows the query will return.
Instead, you should be dynamically building the TableModel by adding a new row to the model in your loop.
See Table From Database, especially the Table From Database Example code for a simple solution that uses the DefaultTableModel.
try this code. im using String connection. this codes is running.
String sql = "select * from tblstudent";
try{
database.Query(sql);
int inc=0;
while(database.dataTable.next()){
Object a = database.dataTable.getInt("StudentID");
Object b = database.dataTable.getString("Firstname");
Object c = database.dataTable.getString("Lastname");
Object d = database.dataTable.getString("Gender");
Object e = database.dataTable.getInt("CourseID");
tblStudent.getModel().setValueAt(a, inc, 0 );
tblStudent.getModel().setValueAt(b, inc, 1);
tblStudent.getModel().setValueAt(c, inc, 2);
tblStudent.getModel().setValueAt(d, inc, 3);
tblStudent.getModel().setValueAt(e, inc, 4);
inc++;
}
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null, "Error");
}
}
Because i is reset to 0 every while loop.So you should put int i=0; before while().
int i=0;
while(rs.next()){
...
}
I have done enough searches to solve my problem which i have done partly but there's this one bug that keeps disturbing me.I am trying to fetch data from a database based on a condition.I have a table 'user_branch' with a foreign key column branchID which is supposed to fetch the coresponding branchNames in another table 'branches' and I am supposed to display the results into a JTable.When i do System.out.println i get all my results but it returns only the last row when i display in a JTable(branchJTable).This is the code i am using
int row = user2BAssignedJTable.getSelectedRow();
assignUserID.setText(user2BAssignedJTable.getModel().getValueAt(row, 0).toString());
user2BAssignedField.setText(user2BAssignedJTable.getModel().getValueAt(row, 1).toString());
try {
String userBrQry = "SELECT branchID FROM user_branch WHERE userID IN(?) ";
String brQ = "SELECT branchName FROM branches WHERE branchID IN(%s) ";
pstmt = con.prepareStatement(userBrQry);
pstmt.setString(1, assignUserID.getText());
results = pstmt.executeQuery();
results.last();
int nRows = results.getRow();
results.beforeFirst();
while (results.next()) {
String branchIDS = results.getString("branchID");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nRows; i++) {
builder.append("?");
if (i + 1 < nRows) {
builder.append(",");
}
}
brQ = String.format(brQ, builder.toString());
PreparedStatement ps = con.prepareStatement(brQ);
for (int i = 0; i < nRows; i++) {
ps.setString(i + 1, branchIDS);
}
ResultSet rs = ps.executeQuery();
//branchJTable.setModel(DbUtils.resultSetToTableModel(rs));
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
while (rs.next()) {
String branchname = rs.getString("branchName");
model.addRow(new Object[]{branchname});
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Forget about the first 3 rows as it is a another JTable event i use to get the userID to use as a condition for getting a particular user's branches assigned to him.
The branches assigned to a user is dynamic hence using StringBuilder.
I am supposed to display the results into another JTable called branchJTable which only displays the last row.Any HELP would be appreciated!
From your question, I think you should declare the JTable
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
before your first loop -
i.e. before while (results.next()) { in your code.
Otherwise in loop, for each loop execution,
the JTable Model is initialising and you are getting the last inserted row in Jtable.