Printing the ASM code to generate the given class - java

I am using eclipse for executing the java program for simple JDBC connection with MySQL with the code as follows:
package samm;
import java.sql.*;
public class Sd {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sam", "root", "1234");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from sam1");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I am unable to execute and get the desired result but instead, I'm getting an error message as:" Prints the ASM code to generate the given class.
Usage: ASMifier [-debug] "

This line can make a problem :
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
Why because this way is used when you define the name of the attributes in your query so instead of :
select * from sam1
Your query should look like this :
select attribute1, attribute2, attribute3 from sam1
Second solution instead of defining the index of the attribute you can use your query as it is but you have to change :
rs.getInt(1)
To this :
rs.getInt("name_of_the_attribute");// for example rs.getInt("id")

Related

capture sql developer script output in java

As part of my java application, I have to create oracle packages from java code. Sometimes, the package code might have issues and compilation might fail. However, I am unable to capture simple failures from java. So, i have to compile > 350 oracle packages from java, and if there are errors in the package, I need to inform the user to fix them. I have pasted oracle package and java code below.
CREATE OR REPLACE PACKAGE plat_test IS
FUNCTION getmsg (
p_empno IN NUMBER
) RETURN VARCHAR2;
END plat_test;
/
CREATE OR REPLACE PACKAGE BODY plat_test AS
FUNCTION getmsg (
p_empno IN NUMBER
) RETURN VARCHAR2 IS
BEG
RETURN 'sss';
END getmsg;
END plat_teest;
Compiling / running the above code in sql developer throws:
LINE/COL ERROR
--------- -------------------------------------------------------------
0/0 PL/SQL: Compilation unit analysis terminated
1/14 PLS-00201: identifier 'PLAT_TEEST' must be declared
1/14 PLS-00304: cannot compile body of 'PLAT_TEEST' without its specification
Errors: check compiler log
I want to create the above package in java and get the result. So that I can inform the user on the failure. In java I am not able to capture the errors and the program always succeeds.
How can I capture the output in java
The java code I have:
import java.sql.*;
public class NewJDBCTester {
public static void one() {
String s_sql = "CREATE OR REPLACE PACKAGE BODY plat_test AS\n" +
" FUNCTION getmsg (\n" +
" p_empno IN NUMBER\n" +
" ) RETURN VARCHAR IS\n" +
" BEG" +
" RETURN 'ret_val';\n" +
" END getmsg;\n" +
"\n" +
"END plat_test\n" +
"/";
// String s_sql ="alter table Metric_idf from ssssssss_ssst";
// System.out.println(" SQL Stmt: " + sql);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection("jdbc:oracle:thin:bhasoor/password#10.100.1.61:34171/ssssssssssdb");
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
try {
stmt.execute (s_sql);
System.out.println(" SQL Executed Successfully ");
} catch (SQLException sqe) {
System.out.println("Error Code = " + sqe.getErrorCode());
// sqe.
System.out.println("SQL state = " + sqe.getSQLState());
System.out.println("Message = " + sqe.getMessage());
System.out.println("printTrace /n");
sqe.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException {
one();
}
}
You can know if an error occurs by this way:
boolean result = stmt.execute(s_sql);
System.out.println(result ? " SQL Executed Successfully " : " SQL Executed with error ");
Then, the following query give you the error:
select *
from ALL_ERRORS
where owner = 'METRICSTREAM'
and name = 'PLAT_TEST'
--and type = 'PACKAGE BODY'
order by sequence
Here, there is no SQLException because the compilation has been completed, but with some errors.
You should use try-with-resource like this to avoid memory leaks:
try ( //
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#10.100.1.61:34171/pdb", "metricstream", "password"); //
Statement stmt = conn.createStatement(); //
) {
boolean result = stmt.execute(s_sql);
System.out.println(result ? " SQL Executed Successfully " : " SQL Executed with error ");
}
catch (SQLException sqe) {
System.out.println("Error Code = " + sqe.getErrorCode());
System.out.println("SQL state = " + sqe.getSQLState());
System.out.println("Message = " + sqe.getMessage());
System.out.println("printTrace /n");
sqe.printStackTrace();
}
You could have a look at this blog from a few years ago.
You can use the libraries from Oracle SQLDeveloper or Oracle SQLcl to run scripts like you would on the command line.
https://barrymcgillin.blogspot.com/2018/04/run-your-sql-script-from-java-now.html
In your script, you can do simple sqlplus things like
Begin
my stuff;
end;
/
show errors
You can also get the errors from the executor object after it has run.
So finally I acheived this like this. Execute the create or replace package then get the errors from dba_errors...
Posting code here...
import java.sql.*;
public class NewJDBCTester {
public static void one() throws ClassNotFoundException {
String s_sql = "CREATE OR REPLACE PACKAGE BODY plat_test AS\n" +
" FUNCTION getmsg (\n" +
" p_empno IN NUMBER\n" +
" ) RETURN VARCHAR2 IS\n" +
" BEGIN\n" +
// " RETURN 'sss';\n" +
" END getmsg;\n" +
"END plat_test;\n";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = DriverManager.getConnection("jdbc:oracle:thin:user/password#10.100.1.61:34171/somedb");
stmt = conn.createStatement();
System.out.println("EXECUTING QUERY");
rset = stmt.executeQuery(s_sql);
rset.close();
stmt.close();
stmt = conn.createStatement();
rset = stmt.executeQuery("SELECT line, text FROM DBA_ERRORS WHERE OWNER = 'Bhasoor' AND NAME = 'PLAT_TEST' ORDER BY SEQUENCE desc");
while (rset.next()) {
System.out.println("ERROR AT LINE ::: " + rset.getString("line"));
System.out.println("\n");
System.out.println("ERROR DETAILS::: " + rset.getString("text"));
}
} catch (SQLException sqe) {
System.out.println("Error Code = " + sqe.getErrorCode());
System.out.println("SQL state = " + sqe.getSQLState());
System.out.println("Message = " + sqe.getMessage());
System.out.println("printTrace \n");
sqe.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException {
one();
}
}

load data from database to another one using java

I have an old database and i want to load the new data from that database every hour into a new database (That i created) using a java code..
i tested that just in two simple databases using this code but it doesn't work for me , can any of u help me or give me some ideas:
import java.sql.*;
class DB{
public static void main(String args[]) {
try {
//loading the jdbc driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/b", "root", "");
Statement stmt = con.createStatement();
//int rows = stmt.executeUpdate("INSERT INTO b.table2 SELECT * FROM a.table1");
ResultSet rs = stmt.executeQuery("INSERT INTO b.table2 SELECT * FROM a.table1");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}}
Your code as printed will work fine. INSERT statements do not return a resultset; they return a single number that represents how many rows were affected. Your commented out code is therefore correct; your uncommented line (using .executeQuery) isn't useful here and probably won't work.

java sqlite - Error: function not yet implemented for SQLite

I created the following class in java to make using SQLite easier when I code.
import java.sql.*;
public class Dbm {
//We want to use the connection througout the whole class so it is
//provided as a class level private variable
private Connection c = null;
//This constructor openes or creates the database provided by the arguement
//NameOfDatabase
public Dbm(String NameOfDatabase){
try {
//Database is checked for in project folder, if doesnt exist then creates database
c = DriverManager.getConnection("jdbc:sqlite:" + NameOfDatabase);
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Opened database successfully");
}
public void CloseDB(){
try{
c.close();
System.out.println("Closed Database Successfull");
}
catch (Exception e){
System.out.println("Failed to close Database due to error: " + e.getMessage());
}
}
public void ExecuteNoReturnQuery(String SqlCommand){
//creates a statment to execute the query
try{
Statement stmt = null;
stmt = c.createStatement();
stmt.executeUpdate(SqlCommand);
stmt.close();
System.out.println("Sql query executed successfull");
} catch (Exception e){
System.out.println("Failed to execute query due to error: " + e.getMessage());
}
}
// this method returns a ResultSet for a query which can be iterated throughd
public ResultSet ExecuteSqlQueryWithReturn(String SqlCommand){
try{
Statement stmt = null;
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(SqlCommand);
return rs;
}catch (Exception e){
System.out.println("An Error has ocured while executing this query" + e.getMessage());
}
return null;
}
}
Here is the main code in the program
import java.sql.*;
public class InstaText {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Dbm db = new Dbm("people.db");
ResultSet rs = db.ExecuteSqlQueryWithReturn("select * from people;");
try{
String name = "";
int age = 0;
String address = "";
while (rs.isLast() == false){
name = rs.getString("name");
age = rs.getInt("age");
address = rs.getString("address");
System.out.println("Name is " + name +" age is " + age + " Address is " + address);
rs.next();
}
}catch (Exception e ){
System.out.println("Error: " + e.getMessage());
}
db.CloseDB();
}
}
But when I execute it I get the following output:
Opened database successfully
Error: function not yet implemented for SQLite
Closed Database Successfull
So how do I solve the Error "Error: function not yet implemented for SQLite"?
I am running the NetBeans Ide with the latest JDBC on mac os sierra.
Edit: Here is the output after adding e.printstacktrace(); in the catch block:
Opened database successfully
Error: function not yet implemented for SQLite
java.sql.SQLException: function not yet implemented for SQLite
Closed Database Successfull
at org.sqlite.jdbc3.JDBC3ResultSet.isLast(JDBC3ResultSet.java:155)
at instatext.InstaText.main(InstaText.java:24)
The problem is not your select query but the isLast() method you are using on the ResultSet instance to retrieve the result. Try the next() method, it should work :
while (rs.next()){
name = rs.getString("name");
age = rs.getInt("age");
address = rs.getString("address");
System.out.println("Name is " + name +" age is " + age + " Address is " + address);
rs.next();
}
You can read here :
https://github.com/bonitasoft/bonita-connector-database/issues/1
that with SQLLite, you may have some limitations with the isLast() method :
According to JDBC documentation
(http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html)
calls to isLast() and first() methods are forbidden if the result set
type is TYPE_FORWARD_ONLY (e.g SQLite).

Searching the Mysql database with Autocomplete on JTable using textfield

Could you please tell me what to add on my code so that when i type a letter in the textfield, before i finish typing the search result already start showing on jtable without waiting for me to type the whole word?
Below please find my code for key released event on the textbox. Thank you for your help.
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE "+selected+" =? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, jTextFieldSearch.getText());
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
//con.close();
}
catch(Exception ex){ex.printStackTrace();}
}
After a two day struggle finally i got an answer...i just needed to use LIKE '%' as shown.No one should suffer as i did
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+"WHERE "+selected+" LIKE ? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1,jTextFieldSearch.getText() + "%");
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
con.close();
}
catch(Exception ex){ex.printStackTrace();}
}

Connecting to database with Java

In preparation for an exam I am asked to debug and answer the questions below, but this goes over my head. Help much appreciated.
Assuming the syntax is correct, why will this code produce an
error when connecting to the database?
Suggest two ways how to improve security of database connection in this code.
import java.sql.*;
public class UpdateCar {
public static void updateCarNum (int carNo, int empNo)
throws SQLException {
Connection con=null;
PreparedStatement pstmt=null;
try {
con = DriverManager.getConnection(
"jdbc:default:connection");
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = " + empNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
}
finally {
if (pstmt != null) pstmt.close();
}
}
}
Change
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = " + empNo);
pstmt.setInt(2, empNo);
to
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = ?");
pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo);
And you should also read a bit about what JDBC is, and how to use it.
Check your DiverManager. in java there is jdbc driver that may not work with your database . try another driver for your connection

Categories

Resources