I am trying an example to return REFCURSOR using PGJDBC-NG Driver but getting an exception
java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.ResultSet
at FunctionReturnRefCursor.main(FunctionReturnRefCursor.java:42)
Source/Code I am trying is -
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
public class FunctionReturnRefCursor {
public static void main(String[] args) throws Exception {
String createFunction = "CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) "
+ " RETURNS refcursor "
+ " AS $$ "
+ " BEGIN "
+ " OPEN mycurs FOR select * from pg_user; "
+ " END; "
+ " $$ "
+ " LANGUAGE plpgsql";
String runFunction = "{? = call getUsers()}";
Class.forName("com.impossibl.postgres.jdbc.PGDriver");
try (Connection conn = DriverManager.getConnection(
"jdbc:pgsql://localhost:5432/test", "postgres", "password");
Statement statement = conn.createStatement();
CallableStatement cs = conn.prepareCall(runFunction);
) {
// We must be inside a transaction for cursors to work.
conn.setAutoCommit(false);
// create function
statement.execute(createFunction);
// register output
cs.registerOutParameter(1, Types.REF_CURSOR);
// run function
cs.execute();
// get refcursor and convert it to ResultSet
ResultSet resultSet = (ResultSet) cs.getObject(1);
while (resultSet.next()) {
System.out.println(resultSet.getString("usename"));
System.out.println(resultSet.getString("passwd"));
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try this:
import java.sql.*;
public class FunctionReturnRefCursor {
public static void main(String[] args) {
String createFunction = "CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) "
+ " RETURNS refcursor "
+ " AS $$ "
+ " BEGIN "
+ " OPEN mycurs FOR select * from pg_user; "
+ " END; "
+ " $$ "
+ " LANGUAGE plpgsql";
String runFunction = "{? = call getUsers()}";
//Substituted:
Driver driver = null;
try {
driver = new com.impossibl.postgres.jdbc.PGDriver();
DriverManager.registerDriver(driver);
} catch (SQLException e) {
e.printStackTrace();
}//:Substituted
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/test", "postgres", "password");
Statement statement = conn.createStatement();
CallableStatement cs = conn.prepareCall(runFunction);
) {
// We must be inside a transaction for cursors to work.
conn.setAutoCommit(false);
// create function
statement.execute(createFunction);
// register output
cs.registerOutParameter(1, Types.REF_CURSOR);
// run function
cs.execute();
// get refcursor and convert it to ResultSet
ResultSet resultSet = (ResultSet) cs.getObject(1);
while (resultSet.next()) {
System.out.println(resultSet.getString("usename"));
System.out.println(resultSet.getString("passwd"));
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
My program throws an error when I try to execute truncate query using JDBC java with sqlite.
import java.sql.*;
public class sqlTruncate {
public static void main( String args[] ) {
try{
Connection c = null;
Statement stmt = null;
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:Mail.db");
stmt = c.createStatement();
String sql = "TRUNCATE TABLE login";
stmt.executeUpdate(sql);
c.setAutoCommit(true);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
}
I tried to test Derby sample source code. Unfortunately it failed: Cannot connect Derby database: connection refused
I was told that I haven't started a server. Official tutorial:
Doesn't start any server.I have no feedback after C:\Apache\db-derby-10.4.1.3-bin\lib> java -jar derbyrun.jar server start just empty line shows and the derbyrun.jar ends.
Doesn't show how to create server on the specified port
My question is: How to start a server on the specified port so the posted code works:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Restaurants
{
private static String dbURL = "jdbc:derby://localhost:1526/myDB;create=true;user=me;password=mine";
private static String tableName = "restaurants";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public static void main(String[] args)
{
createConnection();
insertRestaurants(5, "LaVals", "Berkeley");
selectRestaurants();
shutdown();
}
private static void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{
except.printStackTrace();
}
}
private static void insertRestaurants(int id, String restName, String cityName)
{
try
{
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
id + ",'" + restName + "','" + cityName +"')");
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void selectRestaurants()
{
try
{
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
int numberCols = rsmd.getColumnCount();
for (int i=1; i<=numberCols; i++)
{
//print Column Names
System.out.print(rsmd.getColumnLabel(i)+"\t\t");
}
System.out.println("\n-------------------------------------------------");
while(results.next())
{
int id = results.getInt(1);
String restName = results.getString(2);
String cityName = results.getString(3);
System.out.println(id + "\t\t" + restName + "\t\t" + cityName);
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void shutdown()
{
try
{
if (stmt != null)
{
stmt.close();
}
if (conn != null)
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept)
{
}
}
}
Setting port numbers
By default, Derby using the Network Server listens on TCP/IP port number 1527. If you want to use a different port number, you can specify it on the command line when starting the Network Server. For example:
java org.apache.derby.drda.NetworkServerControl start -p 1088
However, it is better to specify the port numbers by using any of the following methods
1. Change the startNetworkServer.bat or startNetworkServer.ksh scripts
2. Use the derby.drda.portNumber property in derby.properties
Please refer to:
https://db.apache.org/derby/docs/10.5/adminguide/tadminappssettingportnumbers.html
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()
I am trying to inserting the data into the table using ms access 2007 but getting the exception "java.sql.SqlException: no data found"
My data souce name is employee
import java.sql.*;
class AccessDatabase
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:employee");
Statement st = con.createStatement();
String name = "roseindia";
String address = "delhi";
int i = st.executeUpdate("insert into user(name,address) values
('" + name + "','" + address + "')");
System.out.println("Row is added");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I think you don't have a database created. Following code should work:
import java.sql.*;
class ExecuteSqlQuery {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
String str = "CREATE TABLE user(id INTEGER, " + "name VARCHAR(25), address VARCHAR(100), primary key(id))";
st.executeUpdate(str);
System.out.println("Table is created into the database.");
st.executeUpdate("insert into user(id,name,address) values(1111,'roseindia','Rohini,Delhi')");
System.out.println("Row is inserted.");
st.close();
con.close();
}
catch (Exception ex) {
System.out.println("Unable to connect to database.");
}
}
}
I'm trying to do a simple insert query in mysql using java. How do I determine what the problem is if its not doing what its supposed to do:
import java.util.*;
import java.sql.*;
import javax.swing.JOptionPane;
public class regp {
public regp(String player, int score) {
conc conclass = new conc();
Connection conn = conclass.dbConnect();
try {
PreparedStatement fetchPlayers = conn.prepareStatement("SELECT * FROM players WHERE P_Name='" + player + "'");
ResultSet rs = fetchPlayers.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Already Registered!");
} else {
PreparedStatement createPlayer = conn.prepareStatement("INSERT INTO players(P_Name, Score) VALUES('" + player + "', '" + score + "')");
createPlayer.execute();
JOptionPane.showMessageDialog(null, "Player: " + player + " score: " + score);
JOptionPane.showMessageDialog(null, "Registration Successful!");
JOptionPane.showMessageDialog(null, "Not registered!");
}
} catch (Exception e) {
}
}
}
And heres conc.java which contains the database information:
import java.sql.*;
import java.util.*;
public class conc {
public conc(){
}
public Connection dbConnect() {
try {
String db_connect_string="jdbc:mysql://localhost:3306/questions";
String db_userid="root";
String db_password="1234";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Problem is I don't have any idea if its the query, the prepared statement declaration.
One thing is sure to be working. The part which checks if the player inputted is existing or not.
I already checked if the function is getting the values needed by outputting them using joptionpane message dialog. And it sure receives the correct values. So I'm thinking that maybe the problem is in the query.
You could print the exception that you're catching in your regp constructor:
} catch (Exception e) {
e.printStackTrace();
}
You may also want to look at prepared statements rather than constructing your SQL via string concatenation.