executeQuery Fails when table does not exist - java

I have a system in which there are hundreds of table. So i am getting values from them by making sql query in a loop. But if any table does not exists it quits further execution.
Can i place a condition if any table does not exists then it search for next table....

You can use this. This will return list of tables, iterate though it and see if table exist.
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, null, null,
new String[] {"TABLE"});
while (res.next()) {
System.out.println(
" "+res.getString("TABLE_CAT")
+ ", "+res.getString("TABLE_SCHEM")
+ ", "+res.getString("TABLE_NAME")
+ ", "+res.getString("TABLE_TYPE")
+ ", "+res.getString("REMARKS"));
}

You could just catch the exception:
List<String> tableNames = ...;
Statement stmt = ...;
ResultSet rs = null;
for (String tableName : tableNames) {
String sql = buildQuery(tableName);
try {
rs = s.executeQuery(sql);
useData(rs);
} catch {
log.error ("could not execute query on " + tableName);
} finally {
if (rs != null) {
rs.close();
}
}
}

Related

The resultset returns empty when connecting with MySQL

I'm trying to execute a query in database in MySQL using PreparedStatement and ResultSet.
The problem is that I am getting an empty result set in MySQL, otherwise I get a correct result on Derby.
Connection con= null;
ResultSet reslt =null;
PreparedStatement ps = null;
try
{
//Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/SAIID","SAIID","SAIID");
//con = DriverManager.getConnection("jdbc:derby://localhost:1527/pavillons","saiid","saiid");
String Query =" SELECT * FROM ETUDIANT_PAV WHERE PAVILLONS = ? AND CHAMBRE = ? "
ps = con.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ps.setString(1, "A");
ps.setString(2, "1");
reslt = ps.executeQuery();
//String thequeryresult= reslt.getString("NOM_PRENOM");
//System.out.println ("this is the query result"+thequeryresult);
JOptionPane.showMessageDialog(null, "Query Executed");
//con.close();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
Seeing this lines :
reslt = ps.executeQuery();
//String thequeryresult= reslt.getString("NOM_PRENOM");
If you used that commented line to checked the result, this can't worked. You need to move the cursor of that result set to the first line (start to -1).
For that, use ResultSet.next() that will return true until there is no more row to read.
reslt = ps.executeQuery();
while(reslt.next()){ //read all lines
System.out.println(reslt.getString("NOM_PRENOM"));
}
String selctedItemPAV = indextostring(jComboBox1.getSelectedIndex());
String selctedItemCH = jList1.getSelectedValue();
String Query =" SELECT * FROM etudiant_pav WHERE PAVILLONS = ? AND CHAMBRE = ? " ;
rst = theSelectQuery(Query,selctedItemPAV ,selctedItemCH); //this is the posted function
DefaultListModel listModel = new DefaultListModel();
jList3.setModel(listModel);
System.out.println (selctedItemCH + " doppppppppp " +selctedItemPAV + jComboBox1.getSelectedIndex());
System.out.println ("doppppppppp222222222");
if (rst.isBeforeFirst())
{
System.out.println ("ttttttttttttttttttttttttttttttttttttttttttttt"); //the excution stops here in application.....
jList3.setEnabled(true);
listModel.clear();
jLabel1.setVisible(false);
while (rst.next())
{
String aff="hhh";
aff= rst.getString("NOM_PRENOM");
System.out.println ("dooooooooo"+aff);
listModel.addElement(aff);
}
}
else
{
jLabel1.setVisible(false);
jList3.setEnabled(false);
JOptionPane.showMessageDialog(null, "la chambre est vide ");
}
rst.close();
}
catch (Exception ex){
}

Read a reference cursor which returns a column of string values

I am trying to read ref cursors, which returns only one column, a list of string data.
How can I do it java? Do I have to iterate through each resultset or is there any way so that I could get the entire column in one go. I have 5 ref cursor from the procedure.
rs1= (ResultSet) callableStatement.getObject(1);
rs2= (ResultSet) callableStatement.getObject(2);
rs3= (ResultSet) callableStatement.getObject(3);
while(rs1.next()){
list1.add(rs1.getString(1));
}
while(rs2.next()){
list2.add(rs2.getString(1));
}
while(rs3.next()){
list3.add(rs3.getString(1));
}
May this can help :
ResultSet result=null ;
PreparedStatement pstmt = null;
ArrayList yourlist = new ArrayList();
try
{
String queryString = "select yourfield from ....";
result = pstmt.executeQuery();
while(result.next())
{
yourlist.add(result.getInt("yourfield")); //if you are returning varchar so use getString
}
}
catch (SQLException e){
System.out.println("Exception: " + e.toString() );
}
finally
{
if(result!=null)
result.close();
if(pstmt!=null)
pstmt.close();
}

Why select statement always return the last inserted values?

When I try to Select a record using Prepared Statement it always giving me a last inserted values that I recently add.
First what did I do is to search a record in my first table. If the record is exist the foreign key table will populate the values. My Primary and Foreign Key tables works well. The values populating appropriately to their corresponding components but it's not giving me the right values. Any help?
This is the Primary Key table referencing Foreign Key table which is the 2nd table.
Select Query:
String searchSECTIONNAME = "SELECT * FROM allsections_list WHERE SECTION_NAME = ?";//1st Select Statement
String searchSECTIONSETTINGS = "SELECT allsections_list.`SECTION_ID`, allsections_settings.ADVISER_ASSIGNED, allsections_settings.SECTION_POPULIMIT,\n" +
"allsections_settings.ROOM_ASSGN, allsections_settings.YRLEVEL_ASSGN, allsections_settings.SCHOOL_YEAR, allsections_settings.SESSION_ASSIGNED\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.`SECTION_ID`=allsections_settings.`SECTION_ID`";//2nd Select Statement
So what did I do here is join the SECTION_NAME column to Foreign Key table using Right Join. If the record exist it will join the two tables.
Code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String searchSection = Section_SearchSection_Textfield.getText();
try (Connection myConn = DBUtil.connect();
PreparedStatement myFirstPs = myConn.prepareStatement(searchSECTIONNAME);)
{
myFirstPs.setString(1, searchSection);
try (ResultSet myFirstRs = myFirstPs.executeQuery())
{
int resultCounter = 0;
while (myFirstRs.next())
{
String mySectionName = myFirstRs.getString(2);//Get the value of SECTION_NAME
Section_SectionName_TextField.setText(mySectionName);
Section_SectionName_TextField.setEnabled(true);
try (PreparedStatement mySecondPs = myConn.prepareStatement(searchSECTIONSETTINGS))
{
try (ResultSet mySecondRs = mySecondPs.executeQuery())
{
while (mySecondRs.next())
{
String myAdviserAssigned = mySecondRs.getString(2);
Section_Student_Limit_ComboBox1.setSelectedItem(myAdviserAssigned);
Section_Student_Limit_ComboBox1.setEnabled(true);
String mySectionPopulation = mySecondRs.getString(3);
Section_Student_Limit_ComboBox.setSelectedItem(mySectionPopulation);
Section_Student_Limit_ComboBox.setEnabled(true);
String myRoomAssigned = mySecondRs.getString(4);
Section_Room_Assignment_ComboBox.setSelectedItem(myRoomAssigned);
Section_Room_Assignment_ComboBox.setEnabled(true);
String myYearLevelAssigned = mySecondRs.getString(5);
Section_Session_Level_ComboBox.setSelectedItem(myYearLevelAssigned);
Section_Session_Level_ComboBox.setEnabled(true);
String mySchoolYear = mySecondRs.getString(6);
Section_SchooYear_ComboBox.setSelectedItem(mySchoolYear);
Section_SchooYear_ComboBox.setEnabled(true);
String mySessionAssigned = mySecondRs.getString(7);
Section_Session_Settings_ComboBox.setSelectedItem(mySessionAssigned);
Section_Session_Settings_ComboBox.setEnabled(true);
resultCounter++;
}//end of loop mySecondRs (ResultSet)
}//end of try mySecondRs (ResultSet)
}//end of try mySecondPs (PreparedStatement)
}//end of loop myFirstRs (ResultSet)
if (resultCounter == 1)//If exist
{
JOptionPane.showMessageDialog(null, "Data Found");
}
else//If not exist
JOptionPane.showMessageDialog(null, "No Data Found");
}//end of try myFirstRs (ResultSet)
}//end of try myFirstPs (PreparedStatement)
catch (SQLException e)
{
DBUtil.processException(e);
}//end of catch
}
As you can see here. In my first ResultSet myFirstRs when I search a existing SECTION_NAME the foreign key values will populate. If something something in my loop correct me. Thanks in advanced!
Update!
I add a ORDER BY clause in my 2nd Select Query. Because without this the database will return what it wants, so what did I do is modify the query and add the ORDER BY clause like this:
String searchSECTIONSETTINGS = "SELECT allsections_list.`SECTION_ID`, allsections_settings.ADVISER_ASSIGNED, allsections_settings.SECTION_POPULIMIT,\n" +
"allsections_settings.ROOM_ASSGN, allsections_settings.YRLEVEL_ASSGN, allsections_settings.SCHOOL_YEAR, allsections_settings.SESSION_ASSIGNED\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.`SECTION_ID` = allsections_settings.`SECTION_ID`" +
"ORDER BY allsections_list.SECTION_ID";
Still giving me wrong values when I run the project. I tried to run this in NetBeans query and giving me a values in a ASC order.
I just found a simplest solution. I joined the two tables using Right Join.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String searchSection = Section_SearchSection_Textfield.getText().replace("!", "!!").replace("%", "!%").replace("_", "!_")
.replace("[", "![");
String searchSECTIONSETTINGS = "SELECT allsections_list.SECTION_ID as 'ID', allsections_list.SECTION_NAME as 'Section Name', allsections_settings.ADVISER_ASSIGNED as 'Adviser', allsections_settings.SECTION_POPULIMIT as 'Population',\n" +
"allsections_settings.ROOM_ASSGN as 'Room', allsections_settings.YRLEVEL_ASSGN as 'Year Level', allsections_settings.SCHOOL_YEAR as 'School Year', allsections_settings.SESSION_ASSIGNED as 'Session'\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.SECTION_ID = allsections_settings.SECTION_ID\n" +
"WHERE SECTION_NAME LIKE ? ESCAPE '!'\n" +
"ORDER BY allsections_list.SECTION_ID";
if (searchSection.isEmpty())
{
JOptionPane.showMessageDialog(null, "Please fill up this fields");
}
else
try (Connection myConn = DBUtil.connect();
PreparedStatement myFirstPs = myConn.prepareStatement(searchSECTIONSETTINGS);)
{
myFirstPs.setString(1, "%" +searchSection +"%");
try (ResultSet myFirstRs = myFirstPs.executeQuery())
{
int resultCounter = 0;
while (myFirstRs.next())
{
String name = myFirstRs.getString(2);
sectionJTable.setModel(DbUtils.resultSetToTableModel(myFirstRs));
resultCounter++;
}//end of loop myFirstRs (ResultSet)
if (resultCounter > 0)//If exist
{
JOptionPane.showMessageDialog(null, "Data Found");
}
else//If not exist
JOptionPane.showMessageDialog(null, "No Data Found");
}//end of try myFirstRs (ResultSet)
}//end of try myFirstPs (PreparedStatement)
catch (SQLException e)
{
DBUtil.processException(e);
}//end of catch
}

i want to display special characters from mysql to jtextfield using jbutton.my code is working only numbers

private void jbutton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
MainClass mc=new MainClass();
Connection connection;
connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd);
ResultSet rs;
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr=StrQr + " and pid = " + prid.getText().trim() + " ";
}
if (StrQr.length()==0)
{
JOptionPane.showMessageDialog(null,"Enter search critaria.");
return;
}
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");
while (rs.next()) {
purcst.setText(rs.getString("ppurcst"));
salprc.setText(rs.getString("psalprc"));
prid.setText(rs.getString("Pid"));
prname.setText(rs.getString("Pname"));
category.setText(rs.getString("Pcategory"));
cprc.setText(rs.getString("Pcmprc"));
qnty.setText(rs.getString("Pqty"));
slno.setText(rs.getString("Pslno"));
lpurcst.setText(rs.getString("plpurcst"));
}
rs.close();
}
catch (Exception e)
{
System.err.println(e);
//System.exit(1);
}
}
code display only pid = 104 like numbers .
it cant display special charectors( _,- )pid= A_1103like anybody can help me.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'A' in 'where clause'
i declare pid as varchar in mysql
A_1103 needs to be quoted, otherwise MySQL will try and resolve it to a column value.
... pid = 'A_1103' ...
In fact, you should be relying on PreparedStatement in order to prevent possible SQL injection problems.
See Using Prepared Statements for more details
For example...
Connection connection;
connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd);
ResultSet rs;
// I'm assuming there are other elements to this query that
// may be included, otherwise this is a lot of overhead
// for little benifi...
List values = new ArrayList(5);
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr += " and pid = ? ";
values.add(prid.getText().trim());
}
if (StrQr.length()==0)
{
JOptionPane.showMessageDialog(null,"Enter search critaria.");
return;
}
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
// Bind the values to the parameters
for (int index = 0; index < values.size(); index++) {
st.setObject(index + 1, values.get(index));
}
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");
In prepared statement you have to set a ? or any parameter and bind the value.
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr=StrQr + " and pid = ? ";
}
...
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
if (prid.getText().trim().length()>0 )
st.bind(1prid.getText().trim() )
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");

How to truncate a Postgresql's table from JDBC

I have a Postgresql database and I want to truncate some tables using JDBC. How do I do that?
This is what I tried, but none worked... without even any error being reported:
Using CallableStatement.
try (Connection connection = getConnection();
CallableStatement statement = connection.prepareCall("TRUNCATE " + tableName)) {
return statement.execute();
}
Using Statement.
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
return statement.execute("TRUNCATE " + tableName);
}
Using PreparedStatement.
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement("TRUNCATE " + tableName)) {
return statement.execute();
}
After the truncate, I need to commit:
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
int result = statement.executeUpdate("TRUNCATE " + tableName);
connection.commit();
return result;
}
From the documentation:
TRUNCATE is transaction-safe with respect to the data in the tables: the truncation will be safely rolled back if the surrounding transaction does not commit.
You may run into issues if the table has dependencies. If so, truncate the parent tables first, and also use the CASCADE option.
Connection connection = getConnection();
try {
PreparedStatement statement = connection.prepareStatement("TRUNCATE " + parentTable1, parentTable2, ... + " CASCADE");
try {
return statement.execute();
} finally {
statement.close();
}
} finally {
connection.close();
}
First, if you are truncating a table, you probably want to also RESTART IDENTITY (in addition to possibly doing CASCADE, as John Hogan mentioned).
Second, as far as doing a connection.commit(), the assumption is that you have autocommit set to OFF. My Postgres was set up with it set to ON (apparently, that is sometimes the default).
If it is set to ON, then calling the commit is unnecessary, and will result in the error:
"org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled."
Third, you may not have permission to truncate a table (or restart identity). In that case, you will need to:
DELETE from your_table
SELECT setval('your_table_id', 1)
The following worked for me:
public String truncateTable(String tableName, boolean cascadeFlag) {
String message = "";
try {
connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String truncation = "TRUNCATE TABLE yourSchema." + tableName + " RESTART IDENTITY" + (cascadeFlag ? " CASCADE" : "");
System.out.println("truncateTable: Executing query '" + truncation + "'.");
int result = statement.executeUpdate(truncation);
// connection.commit(); // If autocommit is enabled (which it is for our DB), then throws exception after truncating the table.
statement.close();
connection.close();
} catch (SQLException sqlex) {
message = "Could not truncate table " + tableName + ". " + sqlex.getMessage();
System.err.println(message);
sqlex.printStackTrace();
}
return message;
}
Also:
public int deleteResetTable(String tableName, String fieldName) {
int affectedRows = 0;
try {
connection = DriverManager.getConnection(url, username, password);
String sql = "DELETE FROM yourSchema." + tableName;
PreparedStatement preparedStatement = connection.prepareStatement(sql);
affectedRows = preparedStatement.executeUpdate();
System.out.println("Deleted " + affectedRows+ " rows from table " + tableName + ".");
sql = "SELECT setval('yourSchema." + fieldName + "', 1)";
preparedStatement = connection.prepareStatement(sql);
affectedRows = preparedStatement.executeUpdate();
System.out.println("Reset " + affectedRows+ " values from table " + tableName + ".");
} catch (SQLException ex) {
System.out.println("Failed to delete rows from " + tableName + " " + ex.getMessage());
}
return affectedRows;
}

Categories

Resources