So this is part of my code :
try {
for (int i = 0; i < n; i++){
ResultSet res;
res = bdd.requete(sql);
doSomethingWithRes()
}
}
catch (Exception e) {
e.printStackTrace();
}
I would like to close the resultSet at the end of this block (to save resources), however if I add res.cose(), java will tell me that res may not have been initialized (which is true for n=0). Is there a way to initialize the resultSet without doing a query ?
I also tried
try {
for (int i = 0; i < n; i++){
ResultSet res;
res = bdd.requete(sql);
doSomethingWithRes()
}
}
catch (Exception e) {
e.printStackTrace();
}
if (n>=1)
res.close()
but the compiler doesn't accept it, even though it would work. Is there a way to force the compiler to accept this ?
You would have to increase the scope of the ResultSet instance; only issue is you have more than one and you should close all of them. I would suggest a try-with-resources like
try {
for (int i = 0; i < n; i++){
try (ResultSet res = bdd.requete(sql)) {
doSomethingWithRes();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
Related
I want to be able to sort a table from the database, according to either the quatity or the name, but how do i decided what happens in what case?
Below is the code for the table.
public void tableupdate(JTable jTable1, String fill) {
try {
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:file:D:/Inventory.db", "sa", "");
Statement stat = con.createStatement();
fill = "SELECT * FROM BOOKDESC ";
ResultSet rs = stat.executeQuery(fill);
while (jTable1.getRowCount() > 0) {
((DefaultTableModel) jTable1.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
MySQL is offering a method for sorting data in your SELECT statement, it's called ORDER BY.
Usage is found here.
This way, your code doesn't have to do the work, as your ResultSet already gets sorted data.
I have the following codes snippet. I remove further details. I have a for loop with all the data in it. The I run the for loop for (int i = 0; i < list.getLength(); i++). What happens is that the moment any one of the data cause the sql with error say the data has a slash etc then it cause exception and the rest of the for loop cant continue. How can I like skip the one with the exception and continue with rest?
Here is a the codes.
Connection dbconn = null;
Statement stmt1 = null;
Statement stmt2 = null;
try
{
dbconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "tes1", "te15");
stmt1 = dbconn.createStatement();
stmt2 = dbconn.createStatement();
DateFormat outDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = Calendar.getInstance().getTime();
String value = null;
for (int i = 0; i < list.getLength(); i++)
{
String insertCommand = "INSERT INTO command SET .........";
System.out.println("\n SET INSERT :" + insertCommand);
int count = stmt1.executeUpdate(insertCommand);
}
}
catch (SQLException ex)
{
System.out.println("MyError Error SQL Exception : " + ex.toString());
}
catch (Exception rollback)
{
System.out.println("\nRollback :");
rollback.printStackTrace(System.out);
}
catch (Exception e)
{
System.out.println("\n Error here :");
e.printStackTrace(System.out);
}
finally
{
try
{
if (stmt1 != null)
{
stmt1.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt1 close");
ex.printStackTrace(System.out);
}
try
{
if (stmt2 != null)
{
stmt2.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt2 close");
ex.printStackTrace(System.out);
}
try
{
if (dbconn != null)
{
dbconn.close();
}
else
{
System.out.println("MyError: dbConn is null in finally close");
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for dbConn close");
ex.printStackTrace();
}
}
You need to put the try/catch block inside the for, around executeUpdate(insertCommand);
You need to catch the error in the loop too
....
for (int i = 0; i < list.getLength(); i++) {
try {
String insertCommand = "INSERT INTO command SET .........";
System.out.println("\n SET INSERT :" + insertCommand);
int count = stmt1.executeUpdate(insertCommand);
} catch (Exception e) {
// Better catch the real exception
// Handle the exception
}
}
....
Here are the test code:
GraphDatabaseService graphDS;
for (int i = 0; i < 50; i++) {
Transaction tx = graphDS.beginTx();
try {
Node graphNode = graphDS.createNode();
System.out.println("graphNode.ID:" + graphNode.getId());
graphNode.addLabel(label("person"));
tx.success();
}catch (Exception e) {
tx.failure();
e.printStackTrace();
}finally {
tx.close();
}
}
It sometimes success, sometimes fail, when fail, there is no exceoptions, and it will also output nodeId, but there are no nodes created in database. If fail, it will all fail to create 50 nodes in one loop.
It is very odd, hope somebody could show me why, thanks very much!
I have a result set ResultSet rs=stmt.executeQuery(); I wrote a method to print query results as following
public void printResults(ResultSet rs) {
// Getting column names
int j = 1;
while (true) {
try {
System.out.print(rs.getMetaData().getColumnName(j)+" ");
j++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
// Getting results
while(rs.next()) {
int i = 1;
while (true) {
try {
System.out.print(rs.getString(i)+" ");
i++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
}
}
My issue is : is it a good idea to use try && catch ... I feel that it is not? Does it impact speed? What is a better way?
Thank You
You can get column number by
ResultSetMetaData meta= rs.getMetaData();
int columnNum=meta.getColumnCount();
Loop with this columnNum to get the result as well as column name.
for(int i=1;i<=columnNum;i++){
System.out.print(meta.getColumnName(i)+" ");
}
//Get the data
while(rs.next){
for(int i=1;i<=columnNum;i++){
System.out.print(rs.getString(i)+" ");
}
}
I am trying to create a table with values that are in a String array. I am looking for the best way to loop through it without having to send a bunch of queries. This is what I have but obviously the loop wont work. Anyone have a better way of performing this?
public static void createTable(String table, String[] values) throws SQLException{
try {
Class.forName(driver);
conn = DriverManager.getConnection(connectionURL);
Statement state = conn.createStatement();
for(int x = 0; x < values.length; x++){
state.execute("CREATE TABLE" + table + " ( " + values[x] + " );");
}
conn.commit();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Concatenate the elements of Values array.
StringBuilder sb=new StringBuilder();
sb.append("CREATE TABLE " + table + " ( ");
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i >= values.length-1) {break;}
sb.append(",");
}
sb.append(" )");
state.execute(sb.toString());