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.
Related
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.
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")
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).
I am doing practice for JDBC and using NetBeans 8.1. I created a table in MS Access and wrote a program. But the problem is that when I pass column index then my program runs successfully. But I pass column name as in my table in MS Access then there occurs an error that
Column not found
I am pasting code of my program and try to explain my problem further.
package database;
import java.sql.*;
public class Database {
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:personDSN";
Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "SELECT *FROM students";
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
String Name = rs.getString(2);
String add = rs.getString(3);
String pNum = rs.getString(4);
System.out.println(Name + " " + add + " " + pNum);
}
con.close();
}
catch(ClassNotFoundException | SQLException sqlEx)
{
System.out.println(sqlEx);
}
}
}
As you can see in while loop that i have passed column index in getString() function. In this case my program runs successfully. But when i pass name of field/attribute which is in my database table, then it gives me error that "Column not found". For example if I pass getString("name") then it gives me above error.
Please help me to solve my problem.
Note: I have checked again and again that there is no spelling mistake in my parameter opposite to actual table in ms access.
I am trying to update a table using Java JDBC. The method I am using does not throw any errors but the table is not updating. The create table method is below:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CUSTOMERS2 " +
"(PHONE TEXT PRIMARY KEY NOT NULL," +
" SURNAME TEXT NOT NULL, " +
" FIRSTNAME TEXT NOT NULL, " +
" HOME TEXT, " +
" ADDRESS TEXT, " +
" POSTCODE Text)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Customers2 created successfully");
}
The update method is below:
public static void updateCustomers()
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
pstmt = c.prepareStatement(query); // create a statement
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
pstmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully HELLO");
}
I have tried to find some clear instructions on this but cant find any. I do not really understand JDBC and prepared statement very well
When autoCommit is false (c.setAutoCommit(false);), you must manually commit the transaction...
Add...
c.commit()
After pstmt.executeUpdate();
You code also has a flaw, in that if some kind of error occurs during the preparation or execution of the statement, both the Connection and PreparedStatement could be left open, causing a resource leak
If you're using Java 7+ you can use the try-with-resources feature, for example...
try {
Class.forName("org.sqlite.JDBC");
try (Connection c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db")) {
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
try (PreparedStatement pstmt = c.prepareStatement(query)) {
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
c.commit();
}
} catch (SQLException exp) {
exp.printStackTrace();
}
} catch (ClassNotFoundException exp) {
exp.printStackTrace();
System.out.println("Failed to load driver");
}
This will ensure that regardless of how you leave the try block the resource will be closed.
You might also consider taking a look at the JDBC(TM) Database Access
Your update method will set ADDRESS to 1 if there is any row in table with PHONE = does this work.
Try to put Address in 1st Input parameter and Phone 2nd Input parameter
When a connection is created, it is in auto-commit mode.
We need to use [setAutoCommit] method only when we need to make Auto Commit false and make it manual commit after executing the query.
More details at Oracle site on JDBC Transaction.