Run Java .class from another .class by char content inside table (PostgreSQL) - java

I've a table on PostgreSQL like this:
I want to running another Java .class by the content inside the DATA table.
If the content written FIT1, i want to run the FIT1.class;
So do if the content written FIT2, i want to run the FIT2.class; etc.
I only got my code below, and i think it's not work bcs when it tried to get the content, it got all the contents. So the IF function cant work.
Base on the table, i want to running all the process (7 data).
Is there any solution to fix the code?
package fit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class FIT {
public static void main( String args[] )
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/FIT","admin", "admin");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM DATA;" );
while ( rs.next() ) {
String data = rs.getString("data");
System.out.println( "Data = " + data );
System.out.println();
if (data.equals("FIT1")){
FIT1.main(args);
}
else if (data.equals("FIT2")){
FIT2.main(args);
}
else{
}
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}

instead check data == "FIT1" use equals
try this block code:
if (data.equals("FIT1")){
FIT1.main(args);
}
else if (data.equals("FIT2")){
FIT2.main(args);
}

Related

How to fix table already created and values not showing up in console with SQL in Java?

I'm in a Java class and the assignment is to create a table that will show the first ten values of pre-selected columns. However, when I run my code, with the sql running the way it is it says that my table is already created. I was wondering if there was a way for it to stop erroring out when that happens and to still show my code? Also when I set up a new table, the values that I need, (Income, ID, Pep) won't show up, just the headers I established before the syntax will. How would I make these fixes so it stops erroring out and I see my values in the console log?
This is running in eclipse, extended with prior project files from the class i'm taking. I've tried adding prepared statements, attempted to parse for strings to other variables and attempted syntax to achieve the values I need.
LoanProccessing.java file (Main file):
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoanProcessing extends BankRecords {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
BankRecords br = new BankRecords();
br.readData();
Dao dao = new Dao();
dao.createTable();
dao.insertRecords(torbs); // perform inserts
ResultSet rs = dao.retrieveRecords();
System.out.println("ID\t\tINCOME\t\tPEP");
try {
while (rs.next()) {
String ID= rs.getString(2);
double income=rs.getDouble(3);
String pep=rs.getString(4);
System.out.println(ID + "\t" + income + "\t" + pep);
}
}
catch (SQLException e ) {
e.printStackTrace();
}
String s = "";
s=String.format("%10s\t %10s \t%10s \t%10s \t%10s \t%10s ", rs.getString(2), rs.getDouble(3), rs.getString(4));
System.out.println(s);
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println("Cur dt=" + timeStamp);
Dao.java file:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Dao {
//Declare DB objects
DBConnect conn = null;
Statement stmt = null;
// constructor
public Dao() { //create db object instance
conn = new DBConnect();
}
public void createTable() {
try {
// Open a connection
System.out.println("Connecting to a selected database to create Table...");
System.out.println("Connected database successfully...");
// Execute create query
System.out.println("Creating table in given database...");
stmt = conn.connect().createStatement();
String sql = "CREATE TABLE A_BILL__tab " + "(pid INTEGER not NULL AUTO_INCREMENT, " + " id VARCHAR(10), " + " income numeric(8,2), " + " pep VARCHAR(4), " + " PRIMARY KEY ( pid ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
conn.connect().close(); //close db connection
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}
}
public void insertRecords(BankRecords[] torbs) {
try {
// Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.connect().createStatement();
String sql = null;
// Include all object data to the database table
for (int i = 0; i < torbs.length; ++i) {
// finish string assignment to insert all object data
// (id, income, pep) into your database table
String ID = torbs[i].getID();
double income=torbs[i].getIncome();
String pep=torbs[i].getPep();
sql = "INSERT INTO A_BILL__tab(ID,INCOME, PEP) " + "VALUES (' "+ID+" ', ' "+income+" ', ' "+pep+" ' )";
stmt.executeUpdate(sql);
}
conn.connect().close();
} catch (SQLException se) { se.printStackTrace(); }
}
public ResultSet retrieveRecords() {
ResultSet rs = null;
try {
stmt = conn.connect().createStatement();
System.out.println("Retrieving records from table...");
String sql = "SELECT ID,income,pep from A_BILL__tab order by pep desc";
rs = stmt.executeQuery(sql);
conn.connect().close();
} catch (SQLException se) { se.printStackTrace();
}
return rs;
}
}
Expected results would be printlns for the table functions (inserting records and so on), the headings, the data values for the first 10 files, and the date and time of when the program was run. Actual results were some of the table functions, headings and then the time when the program ran not including when it errors me out with table already created. I'm not exactly sure where or how to fix these issues.
you're getting this exception because every time you run your code, your main method calls dao.createTable();, and if the table is already created, it will throw an exception. So for this part, use a verification to check if the table is already created.
I'm not really sure where you created the variable torbs, but also make sure its properties are not null before inserting them to the database.

Stored procedure in derby

I am Trying to write a stored procedure in derby Database.
I wrote a Java file which executes as expected.
This is my java File
package javaapplication8;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JavaApplication8 {
public static void procedure(int uid, String Domain) {
Connection con;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Love_To_Learn", "Mohammed_Numan", "mohammed");
String sql = "Update Intrests set Points = Points + 10 where User_Id = " + uid + " and Intrest = '" + Domain + "'";
PreparedStatement pst = con.prepareStatement(sql);
int x = pst.executeUpdate();
if (x == 1) {
System.out.println("Finally");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I installed the jar file in the database by using.
CALL sqlj.install_jar( 'C:\Users\flipkart\My Documents\NetBeansProjects\JavaApplication8\dist\JavaApplication8.jar', 'Mohammed_Numan.JavaApplication8',0);
And
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.classpath','Mohammed_Numan.JavaApplication8');
Created a Procedure Using
CREATE PROCEDURE Final(IN ID INTEGER,
IN Dom VARCHAR(40))
LANGUAGE JAVA
PARAMETER STYLE JAVA
EXTERNAL NAME 'javaapplication8.JavaApplication8.procedure';
This gives me no error.
Now i called the Procedure Using
call Final(10006,'Java');
Even this executes.But the table is not Updated.
Any reason For This?
I even Called this using callable Statement.
The code is
CallableStatement cst = con.prepareCall("Call Final (?,?)");
cst.setInt(1,Integer.parseInt(u.getString(1)));
cst.setString(2,v.getString(1));
boolean done = cst.execute();
if(done){
System.out.println("Done")
}
else{
System.out.println("Sorry");
}
And i always get Sorry..!Where Am i Going Wrong?Please Check out.

java.sql.SQLException: No current row in the ResultSet

I'm using the jtbs.jdbc.Driver to verify that a proxy number is stored in my MySQL database.
The problem is that whenever I try to copy the curtain row from the table and put it in my ResultSet, the error says that
there is no current row in the ResultSet
The error is at line 31 String value = result.getString(i);
i have been looking all over the web for answers but none of them seem to help my specific predicament.
UP DATE
so far i added a while(result.next()) and it basically dose nothing the while(result.next()) dose not execute.
Here's my code!!!
package dataBata;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class apples {
ArrayList<String> myList = new ArrayList<String>();
String proxNumber = "2435847564";
String usersName = "user";
String password = "pass";
public void wrightMatchdb(){
Connection conn = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/model";
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(url, usersName, password);
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("select replace(PROXID , ' ','') PROXID ,FIRST_NAME from OKWC_IDCARDS where PROXID = '" + proxNumber + "'");
System.out.println("hello");
while(result.next()){
for(int i=1;i<=6;i++){
System.out.println("hello2");
String value = result.getString(i);
if(result.getString(i) != null){
value = value.replace(" ","");
myList.add(value);
}
String userProx=myList.get(i);
String userFName=myList.get(i+1);
JOptionPane.showMessageDialog(null, userProx + " has a match for", "hi " + userFName, JOptionPane.DEFAULT_OPTION);
}
System.out.println("hello3");
};
System.out.println("hello4");
statement.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (conn != null) try { conn.close(); } catch(Exception e) {}
}
}
public static void main(String[] args){
apples A = new apples();
A.wrightMatchdb();
}
}
You need to call result.next() before calling result.getString(i)
Moves the cursor forward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
As far as I can see, your query returns only 2 columns so if you call result.getString(i), make sure that i is either 1 or 2 otherwise you will get an exception.

I'm trying to connect my databse on java, what might be the cause of error?

What I want is to get data from my database which I saved on my workspace folder, I also installed the latest sqlite-jdbc jar...
I followed the tuts here http://www.tutorialspoint.com/sqlite/sqlite_java.htm
here is my code:
import java.sql.*;
import javax.swing.*;
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TR.sqlite","","");
JOptionPane.showMessageDialog(null, "Connection Successful");
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM admin_tbl;");
while ( rs.next() ) {
int id = rs.getInt("admin_id");
String user = rs.getString("username");
String pass = rs.getString("password");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + user );
System.out.println( "ADDRESS = " + pass );
System.out.println();
}
rs.close();
stmt.close();
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
System.out.println(e);
return null;
}
}
}
First i get the result of "Connection Successful" then
I get this error...
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: admin_tbl)
I think you need to give the path of your database file. Presently the driver manager is not able to find the database in which you table is present.
Try like this:
String path=this.getClass().getResource("somedatabase.db").getPath();
conn = DriverManager.getConnection("jdbc:sqlite:"+path);
where path of the path of the database file in your system.

Why ‘No database selected’ SQLException? [duplicate]

This question already has answers here:
java.sql.SQLException: No database selected - why?
(4 answers)
Closed 3 years ago.
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected"
//import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.Vector;
public class DataBase {
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
// 2.open a data source name by means of the jdbcodbcdriver.
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin");
Statement stmt = con.createStatement();
// Shut off autocommit
con.setAutoCommit(false);
System.out.println("1.Insert 2.Delete 3.Update 4.Select");
Scanner s = new Scanner(System.in);
int x;
x = s.nextInt();
String query; // SQL select string
ResultSet rs; // SQL query results
boolean more; // "more rows found" switch
String v1, v2; // Temporary storage results
Vector<Object> results = new Vector<Object>(10);
if (x == 1) {
try {
stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) ");
} catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();}
}
if (x == 2) {
try {
stmt.executeUpdate("DELETE from employee where emp_id='102' ");
}catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
if (x == 3) {
try {
stmt
.executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; ");
} catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
query = "SELECT * FROM employee ";
try {
rs = stmt.executeQuery(query);
// Check to see if any rows were read
more = rs.next();
if (!more) {
System.out.println("No rows found.");
return;
}
// Loop through the rows retrieved from the query
while (more) {
v1 = "ID: " + rs.getInt("emp_id");
v2 = "Name: " + rs.getString("emp_name");
System.out.println(v1);
System.out.println(v2);
System.out.println("");
results.addElement(v1 + "\n" + v2 + "\n");
more = rs.next();
}
rs.close();
} catch (SQLException e) {
System.out.println("" + results.size() + "results where found.");
}
finally{stmt.close();}
}
public static void main(String[] args) throws SQLException {
String str = "y";
do {
DataBase s = new DataBase();
s.LoadDriver();
DataBase.connect();
Scanner sc = new Scanner(System.in);
System.out.println("DO u Want to PROCEED TO QUERY : ");
str = sc.next();
} while (str !="n");
}
}
Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql.
then
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin");
Statement stmt = con.createStatement();
...
Just from looking at the exception.. I would guess that you are not specifying the database.
How can you do a select on a table without telling it which schema to select from ?
This is typically set in the connection string..
Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool?
If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter.
But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still.
while (str !="n")
That's not how you compare strings in Java.
Found a bug listing at MySQL that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well.
Some things that stick out as odd to me (although no clue if they will have any impact on your error)
You only need to load the Driver Manager once
You aren't closing your connection, so either close it or refactor to use the same one.
Perhaps move these two lines to just before the do loop
DataBase s = new DataBase();
s.LoadDriver();

Categories

Resources