I'm trying to drop some objects in Oracle database using jdbc. I want to skip if specific ORA-04043 error occurs. The followings are the code I built.
This array string variable is SqlList.uninstall_OS_COMMAND_SQL.
public static String[] uninstall_OS_COMMAND_SQL = {
"DROP PACKAGE OS_COMMAND",
"DROP PACKAGE LOB_WRITER_PLSQL",
"DROP TYPE OSCOMMAND_VC2_ARRAY",
"DROP TYPE OSCOMMAND_DIR_ARRAY",
"DROP TYPE OSCOMMAND_DIR_ENTRY",
"DROP TYPE FILE_LIST_TYPE",
"DROP TYPE FILE_TYPE",
"DROP PACKAGE FILE_PKG",
"DROP JAVA SOURCE \"OS_HELPER\"",
"DROP JAVA SOURCE \"FILE_TYPE_JAVA\"",
"DROP PACKAGE FILE_SECURITY"
};
and this is the code.
private void uninstallOS_COMMAND_Step1_For_11g() {
Connection targetDBconn = null;
Statement stmt = null;
try {
targetDBconn = globalTargetConn.connect();
logWriter.writeLogs(logTextArea, LogWriter.INFO, "Uninstalling OS_COMMAND package...");
for (int i = 0; i < SqlList.uninstall_OS_COMMAND_SQL.length; i++) {
stmt = targetDBconn.createStatement();
stmt.setEscapeProcessing(false);
logWriter.writeLogs(logTextArea, LogWriter.INFO, "See the query below...");
logWriter.writeLogs(logTextArea, LogWriter.INFO, "\n"+SqlList.uninstall_OS_COMMAND_SQL[i]);
stmt.executeUpdate(SqlList.uninstall_OS_COMMAND_SQL[i]);
}
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (stmt != null ) try {stmt.close();} catch(SQLException ex) {}
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
If I run this code, it executes just one item in the array and stops the entire method. Please help me..
Create one new method and call the new method inloop
Like
execute(Statement stmt, SQL Command ) throws Exception {
try {
stmt.executeUpdate(SqlList.uninstall_OS_COMMAND_SQL[i]);
} catch(SQLException s) {
//LOG error
if (s.getMessage().contains("ORA-04043")) {
} else {
throw s;
}
} catch (Exception ee) {
throw ee;
}
}
you might consider to put your try and catch inside the loop.
Related
I've got problem with connection to hsqldb using jdbc in java app. After parsing in main class from json to java I get 3 objects in list which i am trying to save to database.
Here is Dao class
public class EventDao {
private static final String URL = "jdbc:hsql:file:C:/Applications/appName//APPFOLDER";
private static final String USER = "sa";
private static final String PASS = "";
private Connection connection;
public EventDao() {
try {
Class.forName("org.hsqldb.jdbcDrive");
connection = DriverManager.getConnection(URL, USER, PASS);
} catch (ClassNotFoundException e) {
System.out.println("Couldnot establish connection");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void save(Event event) {
final String sql = "insert into event(id,state,timestamp,type,host,alert) values (?,?,?,?,?,?)";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, event.getId());
preparedStatement.setString(2, event.getState());
preparedStatement.setString(3, event.getTimestamp().toString());
preparedStatement.setString(4, event.getType());
preparedStatement.setString(5, event.getHost());
preparedStatement.setString(6, event.getAlert().toString());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
And here is main when i am trying to save object Event to db (the list have 3 objects)
public static void main(String[] args) {
EventParser eventParser = new EventParser();
eventParser.mainLoop();
}
public void mainLoop() {
try {
EventDao eventDao = new EventDao();
Map<String, EventWrapper> eventsFromFile = readEventsFromFile();
List<Event> eventsToSave = calculateEventTime(eventsFromFile);
for (Event event : eventsToSave) {
eventDao.save(event);
}
eventDao.close();
System.out.println(eventsFromFile);
} catch (IOException e) {
e.printStackTrace();
}
}
After debuging i found out that connection is null. Any ideas why?
The correct form of the URL is:
URL = "jdbc:hsqldb:file:C:/Applications/appName/APPFOLDER";
The Class.forName("org.hsqldb.jdbcDrive") ensures the HSQLDB jar is on your classpath and loads the JDBC driver class form the jar. This was done without error. The error message indicates there is no driver available for the incorrect jdbc:hsql:file url.
I am getting a Null Pointer Exception while executing the insert query. Everything seems to be fine but the problem still exists.
Code used for Database Connection.
public class DBConnect
{
static Connection c ;
static Statement st ;
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
c=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","ashuthesmartest","ashutosha");
st=c.createStatement();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Database error");
}
}
}
Action Performed on Button Click
private void b3ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
char[] arr = pa1.getPassword() ;
String s2 = Arrays.toString(arr) ;
String s1 = t3.getText() ;
DBConnect.st.executeUpdate("insert into LOGIN values('"+s1+"','"+s2+"')"); **//EXCEPTION IN THIS LINE**
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
The initialization block in which you create the connection and the statement is not a static initialization block.
Therefore, it will only be executed when you create an instance of the class DBConnect.
Since you seem to be using DBConnect only statically, that never happens. Your initialization block should be made static. A static initialization block has the keyword static preceding the left brace:
static {
// try etc.
}
I have different methods, which queries different data from a database, but the main structure of every method is the same. To reduce the code, I want to shrink that but I don't know how. I have tried interfaces but the return statement cannot called from an inner class. (It should be typesafe!)
Structure:
public <special type> getXYdata(some parameters) {
try (Connection connection = mDataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(... special query ...)
) {
// Handle ResultsSet and return object of a special type.
} catch (SQLTimeoutException e) {
throw new ContentManagerException("Query took to long or connection timed out", e);
} catch (SQLException e) {
throw new ContentManagerException("Query or parsing its results failed", e);
}
}
Idea:
private interface QHandler<T> {
String getQuery();
T handleResultSet(ResultSet set) throws SQLException;
}
And then:
private void executeQuery(QHandler handler) throws ContentManagerException {
try (Connection connection = mDataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(handler.getQuery())
) {
handler.handleResultSet(results);
} catch (SQLTimeoutException e) {
throw new ContentManagerException("Query took to long or connection timed out", e);
} catch (SQLException e) {
throw new ContentManagerException("Query or parsing its results failed", e);
}
}
But if I call this private method in one of my data mathods, I cannot return an object from the handleResultSet() methods, because the return statement will affect this interface method. Is there an option, to tell the execiteQuery() method which return type the handler has?
Attention: It has to be type safe, no casting if possible!
Your method should not use a raw QHandler type, and should be generic:
private <T> T executeQuery(QHandler<T> handler) throws ContentManagerException {
try (Connection connection = mDataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(handler.getQuery())
) {
return handler.handleResultSet(results);
} catch (SQLTimeoutException e) {
throw new ContentManagerException("Query took to long or connection timed out", e);
} catch (SQLException e) {
throw new ContentManagerException("Query or parsing its results failed", e);
}
}
Note that you're trying to reinvent Spring's JdbcTemplate. You might consider using it instead of reinventing it.
Maybe you are open for alternative solutions. If you are using Java 8, you can do somehting like this:
Interface MyHandler {
<T> T handle(Connection c);
}
class MyHelperClass {
public <T> T withConnection(MyHandler handler) {
try {
Connection connection = mDataSource.getConnection();
return handler.handle(connection);
} catch (...) {
...
} finally {
...
}
}
}
Usage:
Result r = myHelperObject.withConnection(con -> {
ResultSet results = connection.createStatement().executeQuery(query)
return new Result(..)
});
This way you can use lambda expressions so you do not need to implement various new classes for your handler interface.
This is may one class.
Now i want to create a new class registrationvalidator extending LoginValidator.
i tried by
public class registrationvalidator extends LoginValidator {
}
But its show error in netbeans...What is the soluation?
public LoginValidator() throws SQLException{
try {
connect = new Dbconnect();
st = connect.Statement();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int validator(String mobileNo,String pass){
int ret = 0;
try{
String query="select * from login where mobileNo='"+mobileNo+"'";
res= st.executeQuery(query);
while(res.next()){
String dbMobileNo=res.getString("mobileNo");
String dbPass=res.getString("password");
if(mobileNo.equals(dbMobileNo) && pass.equals(dbPass)){
ret=1;
}
else if(mobileNo.equals(dbMobileNo)){
ret=2;
}
}
}catch(SQLException ex){
System.out.println("Sql Execption: "+ex);
System.out.println("3");
}
return ret;
}
}
A few things here.
You can only define one public class per java file. So your RegistrationValidator class should be in its own java file, separate from the LoginValidator class.
Since you are catching the SQLException and logging some info, you don't need the "throws SQLException" for the constructor signature LoginValidator()
I'm checking the size of my database(when I check the used database size I found it's in floating value) : I'm using this piece of code :
Public class DBSize{
private float dbSize;
public float databaseSize(Float dbSize,String dataSize,String indexsize){
String apps="apps"; // It's my DB name
String query_data = "select table_schema,SUM(data_length+index_length)/1024/1024 AS total_mb,SUM(data_length)/1024/1024 AS data_mb,SUM(index_length)/1024/1024 AS index_mb,COUNT(*) AS tables,CURDATE() AS today FROM information_schema.tables where table_schema='"+apps+"' GROUP BY table_schema ORDER BY table_schema;";
try {
connection = getConnection();
stmt = connection.createStatement();
ResultSet rs=stmt.executeQuery(query_data);
if(rs.next()) //as I'm selecting a particular database's information
this.dbSize=rs.getFloat(2);
this.dataSize=rs.getString(3);
this.indexSize=rs.getString(4);
System.out.println("DB Size : "+this.dbSize);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally
{
try {
if(stmt != null)
stmt.close();
if(connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return dbSize;
}
public float getDbSize(){
return dbSize;
}
}
rs is getting null value(don't know whether unable to fetch the value from database or not),even I have used String type the function but also getting the null value,
Any inputs ...that where I'm going wrong :( :(
Keep those three statements of assignment after if inside a block otherwise only first statement will get executed if the condidion rs.next() evaluates to true and next 2 statements will always execute even if the condidion rs.next() evaluates to false which may cause some exception
if(rs.next()){
this.dbSize=rs.getFloat(2);
this.dataSize=rs.getString(3);
this.indexSize=rs.getString(4);
}