Query Java doesn't execute - java

I'm trying to execute a query on eclipse at my Java program, but it always exit with a exception and don't execute the query, I read a lot of posts here but no one of them could help me with this.
public static ResultSet queryAccAmount;
public static String query = " SELECT COUNT(*) s FROM (SELECT L.ACCNUMBER AS AN, L.PROD AS PRD "
+ " FROM LTRANS(nolock) L, AN(nolock) ANM "
+ " WHERE DATA BETWEEN 20210101 AND 20210228 "
+ " AND L.PRD IN (1, 2, 3) "
+ " AND L.ACCNUMBER = ANM.ACCNUMBER "
+ " AND L.ISS = ANM.ISS "
+ " AND L.PROD = ANM.PROD "
+ " AND L.MESSAGECODE <> 'MESSAGE' "
+ " GROUP BY L.PROD, L.ACCNUMBER) S; ";
public static void main(String[] args) throws InterruptedException {
Connection c = connect();
int accAmount = 0;
try {
queryAccAmount = c.createStatement().executeQuery(query);
accAmount = Integer.parseInt(queryAccAmount.getString(1));
LOG.info("Mounth total: " + accAmount);
} catch (Exception ex) {
System.out.println(ex);
} finally {
TimeUnit.SECONDS.sleep(10);
disconnect();
}
}
The error when execute the program:
JavaError
But at the base have data:
DataBase
I don't know what is wrong with this, who could help me I'm already appreciate!

You need to call executeQuery once and then read the results in loop for example Updating my comment with working example:-
import java.sql.*;
public class JDBCConnector {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "root";
static final String PASS = "mysql";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample

Try to do this in your try:
try {queryAccAmount = c.createStatement().executeQuery(query);
if(queryAccAmount.next){
accAmount = Integer.parseInt(queryAccAmount.getString(1));}
LOG.info("Mounth total: " + accAmount);
} catch (Exception ex) {
System.out.println(ex);
} finally {
TimeUnit.SECONDS.sleep(10);
disconnect();
}

Related

How to tell the mysql table to retrieve the next matching record into my default table model

How do I tell my java program to retrieve the next matching record into my default table model.
Below is my home work so far.using jTable tb1 and default table model dtm is compulsory for me.
private void Show_My_LettersActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(url, "root", "root");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * from LCI where SUB_ID = '" + SUB_ID_.getText() + "' AND L_DATE = '" + DATE.getText() + "'";
ResultSet rs1, rs2, rs3, rs4, rs5, rs6, rs7;
rs1=j.getData("select COUNT(*) from LCI");
try (ResultSet rs = stmt.executeQuery(sql)) {
DefaultTableModel dtm = (DefaultTableModel) tb1.getModel();
while (rs.next()) {
String L_ID_ = rs.getString("L_ID");
String L_DATE_ = rs.getString("L_DATE");
String heading = rs.getString("HEADING");
String sub_id = rs.getString("SUB_ID");
System.out.print("ID: " + L_ID_);
System.out.print(", Letter date: " + L_DATE_);
System.out.print(", Heading " + heading);
System.out.println(", Subject ID " + sub_id);
/* This gives the correct out put when debug is done.
But the below code doesn't retrive the full out put.
It gives only the very first record matching with the user inputs*/
Vector v = new Vector();
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
JOptionPane.showMessageDialog(this, "Done");
dtm.getColumnName(1);
v.addElement(rs.getString(1));
dtm.addColumn(v);
dtm.getColumnName(3);
v1.addElement(rs.getString(3));
dtm.addColumn(v1);
dtm.getColumnName(10);
v2.addElement(rs.getString(10));
dtm.addColumn(v2);
// stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID + 1)FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
dtm.addRow(v3);
//stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID '"+(+1)+"')FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
}
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}// TODO add your handling code here:
}

sqlite query using java

I'm working on shifts manager program which calculates monthly salary and etc.
the program based on SQLite database which keeps getting updated by the user input.
my question is , how can i use the SQLite function in java to retrieve information, lets say monthly salary in one command (i know i can use " select sum(tips) between date1 and date2",but how can i get the function result inside a variable?)
so far i've created a function which gets two dates and retrieves all the shifts salary between these dates and summarise them with ResultSet.
here's my code:
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select tips from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum += rs.getInt("tips");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}
I edited your code.
Note that in case you select the sum of the tips, the column name changes. You also get only one row with one column as your result, so you should not need the while loop anymore.
The sum of the tips is now saved in the variable sum
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select sum(tips) from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum = rs.getInt("sum(tips)");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}

ResultSet returns only the last record from the table

The below java method sets the ResultSet data to a bean class and I am fetching the data. But, the method runHiveQuery() returns only one row that is the last record in the table. While debugging the code i found that the resultset is being looped twice as we have two records. But, while returning the bean class object there is some issue as it retrieves only one record.
Unable to find what is going wrong.
public CSPData getCSPData() throws SQLException {
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
}
return cspdata;
}
public void runHiveQuery() throws SQLException {
CSPData cspdata = hivedao.getCSPData();
String hive_db = "csp";
String dbname = cspdata.getDbName();
String dbservername = cspdata.getDbServerName();
String servername = cspdata.getlServerName();
String drop = "Drop table if exists " + hive_db + "." + "IB_C3_" + dbname + "_" + dbservername;
String insert = "insert into table " + hive_db + "." + "IB_export_log select " + "\'ib_c3_" + dbname + "_"
+ servername + "\' from " + hive_db + "." + "dual limit 1";
System.out.println(drop);
System.out.println(insert);
}
Your code returns the last record since it only returns a single record. You should return a List :
public List<CSPData> getCSPData() throws SQLException {
List<CSPData> result = new ArrayList<>();
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
CSPData cspdata = new CSPData ();
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
result.add(cspdata);
}
return result;
}

How to create a table in access database using java

i need to create a table in access database. For this i tried with the following code
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.execute("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
But it throws the following error " ERROR: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified ".
It is possible with UCanAccess
con = ConnectMdb(homedirectory+"/"+"Centre.accdb");
if (con != null) {
Statement st3 = null;
try {
st3 = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
String sqlq3 = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
// System.out.println(sqlq1);
// ResultSet rs3 = null;
try {
st3.execute(sqlq3);
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
Try this.
Below Corrected Code may help you:
mistake in connection string and while creating table. need to use executeUpdate method
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.executeUpdate("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
The problem is on this line:
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
which you should change to:
String connURL = "jdbc:odbc:DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
i.e. you need to remove the semi-colon between jdbc and odbc.

Getting Fractions of a Cent

Hey guys I just got my first java job but if things go well I may never need to code again.
What I need to do is connect to a database and apply interest to a large number of transactions.
I am having trouble getting the math to work right on my local machine. This must be correct to within a fraction of a cent. Any ideas? Thanks in advance!
public Connection getConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", "MY_USER");
connectionProps.put("password", "MY_PASSWORD");
if (this.dbms.equals("mysql")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + "://" +
"YR1F4K3QAS3RV3R" +
":" + this.portNumber + "/",
connectionProps);
} else if (this.dbms.equals("derby")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + ":" +
this.dbName +
";create=true",
connectionProps);
}
System.out.println("Connected to database");
return conn;
}
public static void ApplyInterestToHighVolumeAccounts(Connection con, String dbName, String InterestToApply)
throws SQLException {
Statement stmt = null;
String query = "select * "from " + dbName + ".HighVolumeAccounts";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String AccountName = rs.getString("AccountName");
int AccountNumber = rs.getInt("AccountNumber");
int Balance = rs.getInt("Balance");
int Interest = InterestToApply
int newBalance = Balance + (Balance * Interest) - (Balance * 0.00000001%)
int AddToRetirement = Balance * 0.000001%
String GetRich = "UPDATE TBL_Accounts SET Balance=Balance" + AddToRetirement + " WHERE AccountName=PrivateAccountInTheCaymens";
ResultSet rs = stmt.executeQuery(GetRich);
String AdjustBalance = "UPDATE TBL_Accounts SET Balance=Balance" + newBalance + " WHERE AccountName=AccountName";
ResultSet rs = stmt.executeQuery(AdjustBalance);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
I think you are really close. BigDecimals would be one way to go.
Use the following code verbatum and you should be fine:
import java.sql.*;
import java.math.BigDecimal;
import java.math.MathContext;
public class adjustaccounts{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://YR1F4K3QAS3RV3R";
static final String USER = "MY_USER";
static final String PASS = "MY_PASSWORD";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM HighVolumeAccounts";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int accountnumber = rs.getInt("AccountNumber");
BigDecimal balance = rs.getBigDecimal("Balance");
String accountname = rs.getString("AccountName");
double pennyshave = 0.000000001;
BigDecimal difference = balance.multiply(new BigDecimal(pennyshave));
//Pad your account
sql = "UPDATE TBL_Accounts SET Balance=Balance +" + difference + " WHERE AccountNumber=00098793302999"; //don't worry about this number, its a Java thing
stmt.executeQuery(sql);
//Adjust the other one.
sql = "UPDATE TBL_Accounts SET Balance=Balance -" + difference + " WHERE AccountName="+ accountname;
stmt.executeQuery(sql);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}

Categories