PgSQL Exception: column name not found - exception

I am using postgresql-8.3-603.jdbc4.jar with jdk 1.6 in my application to do the db operations. I am getting the below exceptions at sometimes and doing restart helps to avoid this exceptions temporarily.
org.postgresql.util.PSQLException: The column name sender_id was not found in this ResultSet.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.findColumn(AbstractJdbc2ResultSet.java:2502)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getString(AbstractJdbc2ResultSet.java:2345)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at com.netcore.bulkrequest.db.FeedDAO.setFeedDetails(FeedDAO.java:142)
at com.netcore.bulkrequest.feed.Feed.getInstance(Feed.java:37)
at com.netcore.bulkrequest.core.BulkRequestTask.(BulkRequestTask.java:86)
at com.netcore.bulkrequest.core.BulkRequestValidate.getBulkRequestTaskObject(BulkRequestValidate.java:104)
at com.netcore.bulkrequest.core.BulkRequestValidate.run(BulkRequestValidate.java:57)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Here is the code snippet:
public class FeedDAO {
/**
* Database connection pool object
*/
private final DBContext dbc;
private final Feed feed;
public static final String SENDER_ID_ATTRIBUTE = "sender_id";
/**
* Constructor
*
* #param dbc
* #param feed
*/
public FeedDAO(DBContext dbc, Feed feed) {
this.dbc = dbc;
this.feed = feed;
}
public void setFeedDetails() throws SQLException {
String feedDetailsQuery = "SELECT a.priority, b.keyword, b.welcome " +
" FROM feed AS a, pub_feed_info AS b " +
" WHERE a.resource_id = b.resource_id AND b.resource_id = ?";
String senderIdQuery = "SELECT b.attribute_value AS " +
SENDER_ID_ATTRIBUTE + " FROM " +
"attribute_master AS a, feed_attributes AS b " +
"WHERE a.attribute_id = b.attribute " +
" AND a.attribute_name='" + SENDER_ID_ATTRIBUTE + "' " +
" AND feed_id = ?";
Connection con = null;
PreparedStatement fdStmt = null;
PreparedStatement siStmt = null;
try {
con = dbc.getConnection();
//Get the feed details
fdStmt = dbc.getPreparedStatement(con, feedDetailsQuery);
fdStmt.setInt(1, this.feed.getFeedId());
fdStmt.execute();
ResultSet fdResults = fdStmt.getResultSet();
while (fdResults.next()) {
String keyword = fdResults.getString("keyword");
String welcomeMsg = fdResults.getString("welcome");
int priority = fdResults.getInt("priority");
if(null != keyword) {
this.feed.setKeyword(keyword);
} else {
this.feed.setKeyword(String.valueOf(this.feed.getFeedId()));
}
this.feed.setWelcomeMsg(welcomeMsg);
this.feed.setPriority(priority);
}
//Get the sender id
siStmt = dbc.getPreparedStatement(con, senderIdQuery);
siStmt.setInt(1, this.feed.getFeedId());
if(siStmt.execute()) {
ResultSet siResults = siStmt.getResultSet();
while(siResults.next()) {
String senderId = siResults.getString(SENDER_ID_ATTRIBUTE);
this.feed.setSenderId(senderId);
}
} else {
this.feed.setSenderId(Feed.DEFAULT_SENDER_ID);
}
} catch (SQLException ex) {
throw ex;
} finally {
if (fdStmt != null) { fdStmt.close(); }
if (siStmt != null) { siStmt.close(); }
if (con != null) { con.close(); }
}
}
}
Can anyone please help me to find the permanent fix?
Thanks,
Mani

The key part of the error is "The column name sender_id was not found in this ResultSet" -- te very first row. So, how about showing us the query that's looking for a column that's just not there, and maybe the results of executing that query interactively in pgsql, the relevant parts of your schema, etc? Surely you can't expect us to help you debug without seeing anything more than the exception traceback, with zero clues about your code and DB!

Related

How do I work with aws rds myql on eclipse(Java)?

I have downloaded aws sdk and connected my account and the database. But now I do not know what I need to do next. How do insert, delete or create table through java on eclipse.
I know to do these in a local database. I tried changing the url in getConnection() function to the my endpoint on eclipse but I keep getting error stating
"Access denied for user 'aws'#'xxx.xxx.xxx.xxx' (using password: YES)" (real IP modified for security reasons).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private static final String url = "jdbc:mysql://aws.cyduxshnlizb.ap-south-1.rds.amazonaws.com:3306";
final private String user = "myusername";
final private String passwd = "mypassword";
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection(url,user,passwd);
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from feedback.comments");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into feedback.comments values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from feedback.comments");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from feedback.comments where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from feedback.comments");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}

Getting GWT error while trying to update userinformation stored in mySql

im getting this error - "java.sql.SQLException: Parameter index out of range (6 > number of parameters, which is 5)".
Im trying to update information about my user - trough GWT and MySql - of course
public boolean changePersonInfo(Person person) throws IllegalArgumentException {
try {
PreparedStatement updatePerson = connection.prepareStatement("UPDATE users SET " + "adgangskode = ?, "
+ "email = ?, " + "alder = ?, " + "tlfnr = ?, " + "WHERE id = ?");
updatePerson.setString(1, person.getPassword());
updatePerson.setString(2, person.getEmail());
updatePerson.setString(3, person.getAge() + "");
updatePerson.setString(4, person.getPhonenumber());
updatePerson.setInt(5, person.getId());
int rowsAffected = updatePerson.executeUpdate();
if (rowsAffected == 1) {
return true;
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return false;
Also have this function that should talk with my clickhandler - and RpcServiceImpl
class SettingsClickhandler implements ClickHandler{
#Override
public void onClick(ClickEvent event) {
currentPerson.setPassword(userView.getSettingsView().getPassBoxChange().getText());
currentPerson.setEmail(userView.getSettingsView().getEmailBoxChange().getText());
currentPerson.setAge(Integer.valueOf(userView.getSettingsView().getAgeChangeBox().getText()));
currentPerson.setPhonenumber(userView.getSettingsView().getTlfChangeBox().getText());
// The RPC call which through the server updates the user info in the users table in the database
Service.changePersonInfo(currentPerson, new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
}
/*
* Confirmation if the info was updated
*/
#Override
public void onSuccess(Boolean isUpdated) {
if (isUpdated) {
content.getUserView().getSettingsView();
userView.getSettingsView().clearTextBoxFields();
Window.alert("Aendring lykkes");
}else{
userView.getSettingsView();
Window.alert("Aendring Mislykkes");
}

Search in database with like operator and return list of results

Here is my method to searching a specific String:
(I want to do search in title of books table)
private static String searchInDB(String keyword) {
String url = "jdbc:mysql://localhost/bookstore";
String query = "Select title from books where title like %?% ";
try {
Connection connection = DriverManager.getConnection(...);
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, keyword);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
return rs.getString("title");
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return null;
}
But when i call this method:
System.out.println(searchInDB("so"));
there is an exception in the result:
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which
is 0).
null
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
...
UPDATE
I add this code to get all the results, but i got into a infinitive loop with a identical value!
String result = searchInDB("so");
while (result != null) {
System.out.println(result);
}
Change the code so that the wildcards are contained in the parameter, and not in the query, viz:
String query = "Select title from books where title like ?";
....
ps.setString(1, "%" + keyword + "%");
Edit Re, other question
AFAIK Java has no yield return capability, so you'll need to change your method signature.
Currently, you are returning the first result and then never returning to the function.
My Java is pretty basic, but how about:
private static List<String> searchInDB(String keyword) {
List<String> theStrings = new List<String>();
String url = "jdbc:mysql://localhost/bookstore";
String query = "Select title from books where title like %?% ";
try {
Connection connection = DriverManager.getConnection(...);
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, keyword);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
theStrings.Add(rs.getString("title"));
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return theStrings ;
}

Processing OOP connecting to MySQL database

a friend and I are trying to write a program in Processing. The program needs to be able to connect to our MySQL database pull information at random and display it. we have gotten that much to work. with the following code
import de.bezier.data.sql.*;
MySQL dbconnection;
void setup()
{
size( 100, 100 );
String user = "username";
String pass = "password";
// name of the database to use
String database = "databasename";
// name of the table that will be created
//
String table = "tablename";
//
dbconnection = new MySQL( this, "ip", database, user, pass );
if ( dbconnection.connect() )
{
// now read it back out
//
dbconnection.query( "SELECT COUNT(id) FROM quiz_table" );
dbconnection.next();
int NumberOfRows = dbconnection.getInt(1);
float random = random(1, NumberOfRows);
int roundrandom = round(random);
println(" Row Number: " + roundrandom );
dbconnection.query( "SELECT * FROM quiz_table WHERE id =" + roundrandom);
while (dbconnection.next())
{
int n = dbconnection.getInt("id");
String a = dbconnection.getString("name");
String c = dbconnection.getString("charactor");
String m = dbconnection.getString("game");
int y = dbconnection.getInt("year");
String q= dbconnection.getString("quote");
println(n + " " + a + " " + c + " " + m + " " + y + " " + q);
}
}
else
{
// connection failed !
}
}
void draw()
{
// i know this is not really a visual sketch ...
}
this seems to work fine. however we plan to make the program preform many more tasks and to keep things more manageable we wanted to make somethings objects in this case i want to make an object that will connect to the database when its called. The following is what i have come up with but despite reworking several ways I can't quite get it to work.
import de.bezier.data.sql.*;
MySQL dbconnection;
connect1 myCon;
void setup()
{
size(300,300);
myCon = new connect1("username","password","database","table");
myCon.dbconnect();
}
void draw()
{
}
class connect1 {
String user;
String pass;
String data;
String table;
connect1(String tempuser, String temppass, String tempdata, String temptable) {
user = tempuser;
pass = temppass;
data = tempdata;
table = temptable;
}
void dbconnect(){
dbconnection = new MySQL( this, "ip", data, user, pass );
if ( dbconnection.connect() )
{
// now read it back out
dbconnection.query( "SELECT COUNT(id) FROM table" );
dbconnection.next();
int NumberOfRows = dbconnection.getInt(1);
float random = random(1, NumberOfRows);
int roundrandom = round(random);
println(" Row Number: " + roundrandom );
dbconnection.query( "SELECT * FROM table WHERE id =" + roundrandom);
while (dbconnection.next())
{
int n = dbconnection.getInt("id");
String a = dbconnection.getString("name");
String c = dbconnection.getString("charactor");
String m = dbconnection.getString("game");
int y = dbconnection.getInt("year");
String q= dbconnection.getString("quote");
println(n + " " + a + " " + c + " " + m + " " + y + " " + q);
}
}
else
{
println("fail");
}
}
//end of class
}
Sorry if that is at all hard to understand
The constructor of MySQL expects a PApplet as the first argument. When you call new MySQL(this inside your object, this does no longer refer to the main PApplet as it did in your first program.
The simplest way to fix this might be:
myCon.dbconnect(this); // send the PApplet as argument
...
void dbconnect(PApplet parent) {
dbconnection = new MySQL( parent, "ip", data, user, pass );
...
Another option would be to pass the PApplet to the constructor of your object, storing it in a property, and using that property when calling new MySQL.

Hibernate's session.connection Error: "Too many users"

I am developing a Java web application using Hibernate, but there is a part of it where I want to use JDBC because I am creating look-up tables dynamically.
After a few minutes of using my web app I get this error:
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException:
Data source rejected establishment of
connection, message from server: "Too
many connections"
I know that using session.connection() is deprecated but I just want to get the underlying JDBC connection. I experimented using the session.doWork() but the error still occurred as it had before.
Here is what the code looks like:
Domain Layer:
/**
* Goes through the list of lookupTableAbstractions and persists each one
* #param lookupData
*/
public void updateLookupValues( List<LookupTableAbstraction> lookupData )
{
lookupTablesData.dropAllLookupTables(lookupData);
lookupTablesData.createLookupTables(lookupData);
for (LookupTableAbstraction lookupTable : lookupData)
lookupTablesData.persistLookupTableValues(lookupTable);
}
Data Layer:
public LookupTableAbstraction getLookupTable( String tableName )
{
LookupTableAbstraction lookupTable = new LookupTableAbstraction();
Session session = getSessionFactory().openSession();
String sqlQuery = "select value from " + tableName;
List<String> lookupTableValues = session.createSQLQuery(sqlQuery).list();
session.close();
lookupTable.setTableName(tableName);
for (String value : lookupTableValues)
lookupTable.addValue(value);
return lookupTable;
}
/**
* Persists the passed in lookup table.
* The lookup table that is used is determine by
* the tableName field of the passed in lookupTable
* #param lookupTable
*/
public void persistLookupTableValues( LookupTableAbstraction lookupTable )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = connection.createStatement();
String tableName = lookupTable.getTableName();
for (String value : lookupTable.getValues() )
{
String sql = " insert into " + tableName +
" (value) " +
" values " +
"('" + value + "')";
System.out.println(sql);
stmt.executeUpdate(sql);
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(persistLookupTableValues): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(persistLookupTableValues): " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* Drop's all lookup tables.
* It drops each table based off the lookupTableAbstractions in the passed in list
* #param lookupData
*/
public void dropAllLookupTables( List<LookupTableAbstraction> lookupData )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = null;
for (LookupTableAbstraction lookupTableAbstraction : lookupData) {
stmt = connection.createStatement();
stmt.executeUpdate("drop table " + lookupTableAbstraction.getTableName());
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(dropAllLookupTables): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(dropAllLookupTables): " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* Creates all lookup tables, one for each lookupTableAbstraction
* in the passed in list
* #param lookupData
*/
public void createLookupTables( List<LookupTableAbstraction> lookupData )
{
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Connection connection = null;
try
{
connection = getJDBCConnectionFromHibernate(session);
Statement stmt = null;
for (LookupTableAbstraction lookupTableAbstraction : lookupData) {
stmt = connection.createStatement();
stmt.executeUpdate("create table " + lookupTableAbstraction.getTableName() +
" ( ID int(11) auto_increment, " +
" value text, " +
" primary key (ID) )");
}
stmt.close();
}
catch( Exception e )
{
System.out.println("Exception(createLookupTables): " + e.getMessage());
e.printStackTrace();
}
finally
{
try {
tx.commit();
connection.close();
session.close();
} catch (SQLException e) {
System.out.println("Exception(createLookupTables): " + e.getMessage());
e.printStackTrace();
}
}
}
protected Connection getJDBCConnectionFromHibernate( Session session )
{
return session.connection();
}
Thanks for any suggestions
Same problem here. A lot of the examples on the internet forget to close out the session factory. If you don't close this out you will get the mysql "too many connections" error. Close it out with this line of code:
fact.close();
Assuming you named it fact like this:
SessionFactory fact = new Configuration().configure().buildSessionFactory();
I fixed the problem.
I was creating the session factory over and over.
So, I did this:
protected static SessionFactory sessionFactory = null;
static
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
/**
* Returns a Hibernate session factory
* #return
*/
protected static SessionFactory getSessionFactory()
{
return sessionFactory;
}