I have a bit of a problem with inserting some data in the database. The data is being read by an CSV parser and changed to data besides that, I continue to get this error message:
Connected to the PostgreSQL server successfully.
Naam van de garage: P_Erasmusbrug, Longditude: 4.482313155, Latitude: 51.91024645
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65)
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128)
at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:1023)
at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:374)
at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:358)
at Database.ConnectDatabase.parser(ConnectDatabase.java:80)
at Events.CSVReader.main(CSVReader.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Thank you for your service.
Naam van de garage: P_St.Jacobsplaats, Longditude: 4.482054381, Latitude: 51.92410235
Thank you for your service.
Naam van de garage: P_Schouwburgplein, Longditude: 4.473618335, Latitude: 51.92102728
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
Which continues for all the other lines of data. Is there maybe a way to fix this as I don't really understand what the error message includes..
The a, b2, and c2 are variables for the ''name'' , ''londitude'' and ''latitude''.
package Database;
import java.io.*;
import java.sql.*;
import java.util.HashMap;
import java.sql.SQLException;
public class ConnectDatabase {
private final String url = "jdbc:postgresql://localhost/Project3";
private final String user = "postgres";
private final String password = "kaas123";
private Connection conn;
public Connection connect() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.");
} catch (SQLException exception) {
System.out.println(exception.getMessage());
}
this.conn = conn;
return conn;
}
public HashMap getGarages() {
HashMap<String, Double> newHashMap = new HashMap<String, Double>();
try {
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT deelgemeente, COUNT(garagenaam) FROM garages GROUP BY deelgemeente");
while (rs.next()) {
String deelGemeenteNaam = rs.getString("deelgemeente");
double garageNaamCount = rs.getDouble("COUNT");
newHashMap.put(deelGemeenteNaam, garageNaamCount);
}
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return newHashMap;
}
public HashMap getTheftYear(int year) {
HashMap<String, Double> newHashMap = new HashMap<String, Double>();
try {
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT deelgemeente, percentagediefstal FROM autodiefstal WHERE jaar = " + year);
while (rs.next()) {
String deelGemeenteNaam = rs.getString("deelgemeente");
double deelPercentage = rs.getDouble("percentagediefstal");
newHashMap.put(deelGemeenteNaam, deelPercentage);
}
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return newHashMap;
}
public int parser(String a, float b2, float c2) {
int updated = 0;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(url, user, password);
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(" + a + "," + b2 + "," + c2 + ")";
stmt = conn.prepareStatement(insertSQL);
stmt.setString(1, a);
stmt.setFloat(2, b2);
stmt.setFloat(3, c2);
System.out.println("Inserted data into the database...");
updated = stmt.executeUpdate();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your service.");
this.conn = conn;
return updated;
}
}
You aren't correctly using the ? placeholders system, replace :
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(" + a + "," + b2 + "," + c2 + ")";
with
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(?,?,?)";
Related
Am trying to save some field from my jFrame form but when i click the save button, i get the null pointer exception. Previously i was getting the errors that text field couldn't be null so i unchecked not null but it didn't work , i decided not to include Voucher_no in MySQL insert statement as it is an auto increment and its text field is not editable
Is there any problem with my code?
Am Using Mysql Workbench.
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
con.setAutoCommit(false);
try {
// String kb = jTextField3.getText(); //voucher_no
String kc = (String) jComboBox3.getSelectedItem(); //factory
String kg = jTextField10.getText(); //fuel
Double ks = Double.valueOf(kg);
String ke = jTextField11.getText(); //electricity
Double kt = Double.valueOf(ke);
String kf = jTextField12.getText(); //manpower
Double ku = Double.valueOf(kf);
String kj = (String) jComboBox4.getSelectedItem(); //can_name
String kk = (String) jComboBox5.getSelectedItem(); //label name
String kq = jTextField23.getText();//no_of_cans
Double kv = Double.valueOf(kq);
String kr = jTextField24.getText();//no_of_labels
Double kw = Double.valueOf(kr);
String query1= "insert into production (date,factory,fuel,electricity,manpower,can_name,label_name,no_of_cans,no_of_labels)"
+ "values (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement pst = con.prepareStatement(query1)){
// pst.setString(10, kb);
pst.setString(1, ((JTextField) jDate1.getDateEditor().getUiComponent()).getText());
pst.setString(2, kc);
pst.setDouble(3, ks);
pst.setDouble(4, kt);
pst.setDouble(5, ku);
pst.setString(6, kj);
pst.setString(7, kk);
pst.setDouble(8, kv);
pst.setDouble(9, kw);
pst.execute();
}
try {
int rows = jTable2.getRowCount();
for (int row = 0; row < rows; row++) {
String kd = (String) jTable2.getValueAt(row, 0);
Double kn = (Double) jTable2.getValueAt(row, 1);
try {
// Class.forName("com.mysql.jdbc.Driver").newInstance();
// Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
String query = "insert into production(product_name,product_quantity)"
+ "values (?,?)";
PreparedStatement update = con.prepareStatement(query);
update.setString(1, kd);
update.setDouble(2, kn);
update.addBatch();
update.executeBatch();
con.commit();
} catch (SQLException e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(this, "Error in production Table");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Invalid Entry in fields");
}
} catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "Invalid in fields");
}
} catch (Exception e) {
e.printStackTrace();
}
The code is doing
update.addBatch();
update.executeBatch();
con.commit();
executeBatch and commit must be done outside the loop.
The misunderstanding arises from "addBatch" that should have been named "addToBatch."
Try doing it this way. First create a connection class as follows;
import java.sql.Connection;
import java.sql.DriverManager;
public class db_connection
{
public Connection connection()
throws Exception
{
try
{
Connection conn = null;
String username = "root"; String password = "";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/database";
try {
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
return null;
}
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}return null;
}
}
Then on your save button do something like this,
private void ButtonRegGroup_SubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if ((this.jTextFieldGrp_ReqAmnt.getText().equals(""))
|| (this.jTextFieldGrp_name.getText().equals(""))
|| (this.jTextFieldGrp_Id.getText().equals(""))
|| (this.jTextFieldGrp_prj_name.getText().equals(""))) {
JOptionPane.showMessageDialog(this, "Some fields are empty", this.title, this.error);
} else {
try {
this.con = ((Connection) new db_connection().connection());
this.pst = ((PreparedStatement) this.con.prepareStatement("insert into registered_projects(project_type,name,project_name,project_id,constituency,ward,requested_amount)values(?,?,?,?,?,?,?)"));
GroupRegDetails();
this.pst.setString(1, this.proj_type);
this.pst.setString(2, this.group_name);
this.pst.setString(3, this.proj_name);
this.pst.setInt(4, this.proj_id);
this.pst.setString(5, this.constituency);
this.pst.setString(6, this.ward);
this.pst.setInt(7, this.requested_amount);
int row = this.pst.executeUpdate();
con.commit();
if (row == 0) {
this.con.rollback();
JOptionPane.showInternalMessageDialog(this, "Didn't Register project", this.title, this.error);
}
JOptionPane.showMessageDialog(this, "Project Successfully Registered", this.title, this.infor);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void GroupRegDetails() {
this.group_name = this.jTextFieldGrp_name.getText();
this.proj_id = Integer.parseInt(this.jTextFieldGrp_Id.getText());
this.proj_name = this.jTextFieldGrp_prj_name.getText();
this.constituency = this.jComboBoxGrp_Comb_const.getSelectedItem().toString();
this.ward = this.jComboBoxGrp_comb_Ward.getSelectedItem().toString();
this.requested_amount = Integer.parseInt(this.jTextFieldGrp_ReqAmnt.getText());
this.proj_type = "Group";
}
And finally good practice is to put fields on a Jpanel and the Jpanel on a Jframe. Hope this helps.
I have just created a method in my class file, were I insert data into my sql database.
1) Are these prepared statements correct?
2) I need to return a type car for the method (Where could this be done)?
.....As the error I get at the moment is the method must return a type Car (Car is the name of the class file)
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
Car c = new Car();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, aLicense);
preparedStmt.setInt(2, aJourneys);
preparedStmt.setString(3, aUsername);
preparedStmt.setString(4, aPassword);
preparedStmt.execute();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return c;
}
Calling the method returns an error that the method is not applicable for arguments
//int addingID = Integer.parseInt(enteringID.getText());
String addingReg = enteringReg.getText();
int addingJourneys = Integer.parseInt(enteringJourneys.getText());
String addingUsername = enteringUsername.getText();
#SuppressWarnings("deprecation")
String addingPassword = enteringPassword.getText();
Car newCar = new Car(addingReg, addingJourneys, addingUsername, addingPassword);
int addStatus = myCar.addVehicle(newCar);
if (addStatus == 1) {
JOptionPane.showMessageDialog(null, "Vehicle Added");
enteringID.setText("(eg. 1-999)");
enteringReg.setText("(eg. - 162-MH-749)");
enteringJourneys.setText("(eg. 7)");
enteringUsername.setText("(eg. - username#domain.com)");
enteringPassword.setText("");
}
else {
JOptionPane.showMessageDialog(null, "Error, Please Try Again");
}
} catch (Exception f) {
JOptionPane.showMessageDialog(null, "Error, Please Try Again");
}
}
});
This is not a final answer for your question, but purely to clarify my comment.
If you want your method to return a Car object, you'll have to create an instance of class Car and return it:
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, "'" + aLicense + "'");
preparedStmt.setInt(2, aJourneys);
preparedStmt.setString(3, "'" + aUsername + "'");
preparedStmt.setString(4, "'" + aPassword + "'");
preparedStmt.execute();
conn.close();
Car c = new Car();
//Do anything with the car object that you like.
//for example: c.setColor("blue");
return c;
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
//kayaman is correct here: we still need to return something here in order to be able to compile
return null;
}
Separate the logic!
Use this class to retrieve connection where you need it:
public class DatabaseConnection
{
private static final String CONN_URL = "some connection url";
private static Connection instance = null;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static synchronized Connection getInstance() throws SQLException
{
if (instance == null)
{
instance = DriverManager.getConnection(CONN_URL);
}
return instance;
}
}
Use it in your function like this:
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword)
{
String sql = "insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword) values (?, ?, ?, ?)";
try (Connection conn = DatabaseConnection.getInstance(); PreparedStatement prepStatement = conn.prepareStatement(sql))
{
Car successfulAdd = new Car();
prepStatement.setString(1, aLicense);
prepStatement.setInt(2, aJourneys);
prepStatement.setString(3, aUsername);
prepStatement.setString(4, aPassword);
if (prepStatement.execute())
{
return successfulAdd;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
package com.Foodmart;
import javax.jws.*;
import java.sql.*;
#WebService(name = "FoodMart", serviceName = "FoodMartService", portName = "FoodMartHtt)
public class FoodmartWS {
ProductDetails prod = new ProductDetails();
#WebMethod(operationName = "check")
public boolean Authenticate(String user, String pass) {
PreparedStatement psmt = null;
Connection c = null;
try {
c = ConnectionDB.getConnection();
String selectSQL = "select * from Employee where Username=? and Password=?";
psmt = c.prepareStatement(selectSQL);
psmt.setString(1, user);
psmt.setString(2, pass);
psmt.executeQuery();
c.close();
return true;
} catch (SQLException e) {
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
In this Method Error in AddProduct
#WebMethod(operationName = "AddProduct")
public ProductDetails ProdcutAdd(int prodid, double qty) {
PreparedStatement preparedStatement = null;
Connection con = null;
try {
System.out.println("try");
//here i am not able to create another one connection
con = ConnectionDB.getConnection();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Food", "root", "manager1");
String selectSQL = "select Product_Id,Product_Name,Product_Price,Product_Qty from Products where Product_Id=?;";
System.out.println("bbefore prepared");
preparedStatement = con.prepareStatement(selectSQL);
preparedStatement.setInt(1, prodid);
System.out.println("before result set");
ResultSet rs = preparedStatement.executeQuery();
System.out.println("query Executed");
rs.next();
prod.setProductId(rs.getInt("Product_Id"));
prod.setProductName(rs.getString("Product_Name"));
prod.setProductPrice(rs.getDouble("Product_Price"));
prod.setProductQty(rs.getInt("Product_Qty"));
System.out.println("obj set");
con.close();
System.out.println("in" + prod);
return prod;
} catch (SQLException e) {
System.out.println(e);
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Why you add this line after you get your connection :
con = ConnectionDB.getConnection();
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Food", "root", "manager1");
So just delete it or comment it.
Note
you missed a ") here in the end, so this can also make a problem :
#WebService(name = "FoodMart", serviceName = "FoodMartService", portName = "FoodMartHtt)
Hope this can help you.
Im starting in SQLite, I created my db and the connection works.
When I try to Insert a value (the db is empty) I get the following error:
java.sql.SQLException: near ".684": syntax error
import java.sql.*;
public class connection{
String route = "C:\\Freeman SA.db";
Connection c = null;
Statement stat = null;
String op;
public void connect(){
try{
c = DriverManager.getConnection("jdbc:sqlite:"+route);
if (c!=null)
System.out.println("Connected to db.");
}
catch (SQLException ex) {
System.err.println("Couldn't connect."+ex.getMessage());
}
}
public void insert_DB(String NAME, String LNAME, String ID, int AGE, int TIME, int SALARY) throws SQLException{
connect();
try {
stat = c.createStatement();
op = "INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (" + NAME + ", " + LNAME + ", " + ID + ", " + AGE + ", " + TIME + ", " + SALARY + ");";
stat.executeUpdate(op); //Here is the problem
stat.close();
}
catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
c.close();
}
}
Main.
public static void main(String[] args) throws IOException {
connection n = new connection();
try {
n.insert_DB("Charlie", "White", "18.954.621-K", 21, 2, 650000);
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
PD: I'm learning from here: http://www.tutorialspoint.com/sqlite/sqlite_java.htm
It's a bad idea to create a SQL statement by concatenating Strings like that. Do some research into SQL injection attack and Little Bobby Tables.
PreparedStatement is a better idea. Bind your variables after validation.
See if this makes your life better:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Demo RenumerationDao
* Created by Michael
* Creation date 6/8/2016.
* #link https://stackoverflow.com/questions/37714254/java-how-can-i-insert-values-in-sqlite/37714292#37714292
*/
public class RenumerationDao {
private static final String INSERT_SQL = "INSERT INTO Remuneraciones(Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES(?, ?, ?, ?, ?, ?)";
private Connection connection; // Better to get this from a pool.
public RenumerationDao(Connection connection) {
this.connection = connection;
}
public int insert(String firstName, String lastName, String id, int age, int timeInHours, int salary) {
int numRowsInserted = 0;
PreparedStatement ps = null;
try {
ps = this.connection.prepareStatement(INSERT_SQL);
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, id);
ps.setInt(4, timeInHours);
ps.setInt(5, age); // You'll have to update this each and every year. BirthDate would be better.
ps.setInt(6, salary);
numRowsInserted = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(ps);
}
return numRowsInserted;
}
public static void close(Statement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I am trying to write a runnable jar file that can be able to connect to 2 different databases informix old database and oracle new database. It should be able to update the new database(oracle) with the old database(informix) records.
I re-edit my java code I added separate methods for my select, update and connections I am not getting an error but its not updating my db. My select works but my update statement is not working. This is my result i get - SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE where profile_id = 102
profileid : 102
ingressflag : Y
egress_flag : Y
ceingressflag : Y
ceegressflag : Y
ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
I am not sure how can I fixed the ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
public class TestConnection {
static ResultSet rs;
public static void main (String[] args) throws Exception {
try{
selectRecordsIcore();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE";
try {
dbConnection = getInformixConnection();
statement = dbConnection.createStatement();
System.out.println(selectTableSQL);
// execute select SQL stetement
rs = statement.executeQuery(selectTableSQL);
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
System.out.println("profileid : " + profileid);
System.out.println("ingressflag : " + ingressflag);
System.out.println("egress_flag : " + egress_flag);
System.out.println("ceingressflag : " + ceingressflag);
System.out.println("ceegressflag : " + ceegressflag);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static void updateRecordIntoBids() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
ArrayList<TempStorageRecords> updateSQL = new ArrayList<TempStorageRecords>();
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
String updateTableSQL = "UPDATE traffic_profile SET ingress_flag = " + ingressflag
+ " ,egress_flag = " + egress_flag
+ " ,ce_ingress_flag = " + ceingressflag
+ " ,ce_egress_flag = " + ceegressflag
+ " WHERE profile_id = " + profileid + ";";
try {
dbConnection = getOracleConnection();
statement = dbConnection.createStatement();
System.out.println("updateTableSQL 1 :" + updateTableSQL);
// execute update SQL stetement
statement.execute(updateTableSQL);
System.out.println("updateTableSQL 2: " + updateTableSQL);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
}
public static Connection getOracleConnection() throws SQLException {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#oracle_host:1521:BIDS";
String username = "username";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Oracle driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
public static Connection getInformixConnection() throws SQLException {
String driver = "com.informix.jdbc.IfxDriver";
String url = "jdbc:informix-sqli://informix_host:1615/icore:INFORMIXSERVER=icit";
String username = "user";
String password = "pass";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Informix driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
At first try to export data from source database into text file.
Your code uses hard coded column names, but I think it could read table names to export from some config file and column names from metadata from SELECT * FROM [table_name]. In JDBC there is getMetaData() for RecordSet. Use it.
When you export data into text files without problems you can do the next step: import such data directly from the source database to the destination database.
For destination database create prepareStatement with:
'INSERT INTO ' + table_name_dest + ' (' + column_names +') VALUES ('+ question_marks + ')'
(there question_marks are '?' chars which maps to columns).
Then for each record from source table and for each record (row) do:
insert_stmt.setObject(i, rs_in.getObject(i))
For big tables you can also use setFetchSize() and addBatch()/executeBatch()