How to retrieve data stored in bytea format - postgresql

I have the data in form of json/xml but in the database it is stored in form of bytea, how can i extract it back in form of json/xml.
Here is my query:
SELECT request_payload FROM unirate_incoming_request WHERE id='1224892672'
Output i am getting:
[
org.postgresql.jdbc42.Jdbc42ResultSet#119020fb
]
Here is my database query:
public ResultSet payload(String a) throws SQLException {
ResultSet dboutput;
String query = " SELECT request_payload FROM unirate_incoming_request WHERE id='1224892672';
System.out.println(query);
DatabaseConnection dc = new DatabaseConnection(server, dbName, user, password);
dboutput = dc.executeQuery1(query);
System.out.println("hi");
while (dboutput.next()) {
System.out.print(dboutput.getBytes("request_payload") + " ");
}
dboutput.close();
dc.close();
return dboutput;
}
Here is my database connection:
public ResultSet executeQuery1(String sql) throws SQLException {
logSql(sql);
Statement stmt = createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs;
}

Related

org.postgresql.util.PSQLException: This ResultSet is closed

When I am trying to print the row values from a table in a PostgreSQL database using JDBC with this code
static Connection c = null;
static Statement statement = null;
static Scanner sc = new Scanner(System.in);
public static void displayTable() throws Exception{
ResultSet rs = statement.executeQuery("SELECT * FROM TABLE");
String dataBaseName = "";
String dataBaseNumber = "";
try {
while(rs.next()){
//System.out.println("Resultant set: " + rs);
dataBaseName = rs.getString("name");
dataBaseNumber = rs.getString("number");
System.out.println("Name: " + dataBaseName + "\Number: " + dataBaseNumber);
}
} catch (Exception e) {
System.out.println(e);
}
}
In while loop, after printing first row it gives me exception
org.postgresql.util.PSQLException: This ResultSet is closed.
Can some one please explain what's going on?

Unable to reach my H2 table from Matlab (but able from Java)

The following Java code works:
public class TestH2Schema {
public static void main(String[] args) throws SQLException {
Driver driver = new org.h2.Driver();
Connection conn = driver.connect("jdbc:h2:file:D:/Users/Dims/Design/TESTS/SVHN_DB/db/svhn", null);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM IMAGE WHERE PATH='train/1.png';");
while(rs.next()) {
System.out.println(rs.getLong("ID"));
}
rs.close();
stmt.close();
conn.close();
}
}
The following equivalent code in Matlab does not work:
driver = org.h2.Driver;
props = java.util.Properties;
conn = driver.connect('jdbc:h2:file:D:/Users/Dims/Design/TESTS/SVHN_DB/db/svhn', props);
stmt = conn.createStatement();
query = 'SELECT ID FROM IMAGE WHERE PATH=''train/1.png''';
rs = stmt.executeQuery(query);
while rs.next()
rs.getLong('ID')
end
rs.close();
stmt.close();
conn.close();
doesn't work causing exception
org.h2.jdbc.JdbcSQLException: Table IMAGE not found; SQL statement:
UPDATE
If I query
query = 'SELECT * FROM INFORMATION_SCHEMA.TABLES;'
I see a list of tables, but not mine ones. Looks like Matlab is somehow looking at different location or someting.
matlab search in "MatlabDatabase" (or another default data-source)
to use your own defined data-source you should declare it first
for example:
q1='use your_datasource';
q2='select * from INFORMATION_SCHEMA.TABLES';
exec(conn,q1);
exec(conn,q2);

Unable to know how to link data between two tables

I'm learning RESTful webservices from javabrains website. Here there is a section named Comments and this is related to a message, But I'm unable to know How Can I link these both.
Below is my SQL Tables for Messages and comments.
Messages
Comments
Here Basically, both look pretty same(The table design), but the values differ. And I'm using the below method to send the data.
public Comment addComment(long messageId, Comment comment) throws Exception {
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("/config.properties"));
String userName = properties.getProperty("user");
String password = properties.getProperty("pass");
String url = properties.getProperty("Sqldburl");
int key = 0;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(url, userName, password);
String query = "select count(*) from Comments";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
rs.next();
key = rs.getInt(1);
} catch (Exception e) {
System.out.println(e);
}
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(url, userName, password);
String query = "insert into Comments(id, message, author) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, key);
ps.setString(2, comment.getMessage());
ps.setString(3, comment.getAuthor());
ps.executeQuery();
} catch (Exception e) {
System.out.println(e);
}
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(url, userName, password);
String query = "select * from Comments where messageId=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setLong(1, messageId);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
comment.setAuthor(rs.getString("Author"));
comment.setId(rs.getInt("Id"));
comment.setMessage(rs.getString("message"));
}
} catch (Exception e) {
System.out.println(e + "b3");
}
return comment;
}
After writing this code, I've realized that Here I'm adding a comment for sure into Comments table, But it is no where linked to the Messages.
I know a way, that is I've create a new column in the Comments table and using join operation, I need to update the same messageId in comments table. But I want to know if there is a better way of getting this done, without using the concept of joins.
In MessageBean, there is a map declared as below.
private Map<Long, Comment> comments = new HashMap<>();
#XmlTransient
public Map<Long, Comment> getComments() {
return comments;
}
public void setComments(Map<Long, Comment> comments) {
this.comments = comments;
}
can I take any advantage of this to avoid join?

Postgres jdbc PreparedStatement setObject does not cast values?

I am trying to insert the data onto different databases. Used dbutils to incorporate QueryRunner.batch() for batch inserts. This worked for SQL Server which casts the data to the corresponding type. I tried the same with PostgreSQL but of no avail. I tried a sample insert but that has failed in PostGres which validates my claim whereas the inserts for SQL Server were successful:
private void postGrestest() throws ClassNotFoundException, SQLException
{
Class.forName("org.postgresql.Driver");
String dropStmt = "DROP TABLE PUBLIC.TEST";
String createStmt = "CREATE TABLE PUBLIC.TEST(COL1 VARCHAR(10), COL2 BOOLEAN)";
String insertStmt = "INSERT INTO PUBLIC.TEST(COL1, COL2) VALUES (?, ?)";
try (Connection connection = DriverManager.getConnection(
"jdbc:postgresql://<host>:5432/<dbname>", "<username>", "<password>");
Statement stmt = connection.createStatement();
PreparedStatement ps = connection.prepareStatement(insertStmt);)
{
//stmt.execute(dropStmt);
stmt.execute(createStmt);
Random r = new Random();
for (int i = 0; i < 100; i++)
{
Object str = "Test" + i;
ps.setObject(1, str);
Object obj = String.valueOf(r.nextBoolean());
ps.setObject(2, obj);
ps.executeUpdate();
}
}
}
Exception in thread "main" org.postgresql.util.PSQLException: ERROR:
column "col2" is of type boolean but expression is of type character
varying Hint: You will need to rewrite or cast the expression.
Position: 49
private void sqlserverTest() throws SQLException, ClassNotFoundException
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String dropStmt = "DROP TABLE DBO.TEST";
String createStmt = "CREATE TABLE DBO.TEST(COL1 VARCHAR(10), COL2 BIT)";
String insertStmt = "INSERT INTO DBO.TEST(COL1, COL2) VALUES (?, ?)";
try (Connection connection = DriverManager.getConnection(
"jdbc:sqlserver://<host>:<port>", "<username>", "<password>");
Statement stmt = connection.createStatement();
PreparedStatement ps = connection.prepareStatement(insertStmt);)
{
//stmt.execute(dropStmt);
stmt.execute(createStmt);
Random r = new Random();
for (int i = 0; i < 100; i++)
{
Object str = "Test" + i;
ps.setObject(1, str);
Object obj = String.valueOf(r.nextBoolean());
ps.setObject(2, obj);
ps.executeUpdate();
}
}
}
The reason I have to cast because, I read the data from a file and get as an object array. I do not have idea of the type beforehand and would like to use setObject instead of specific types setBoolean, setInteger, etc.
What other ways that I can use without casting at my application level and let the driver handle the cast?

The column name ... was not found in this ResultSet

We are using java jdk 1.7.0_45, postgresql jdbc connector postgresql-9.3-1100.jdbc41.jar.
Here is a synopsis of our problem, as much as possible of code pasted below.
This code:
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("d.deptId"));
Produces the error:
org.postgresql.util.PSQLException: The column name d.deptId was not found in this ResultSet.
This code:
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("deptId"));
Produces no error.
Is there a way, besides removing the "d." from the first query, to make the first code snippet not throw the error message?
Here is the source code:
public class JoinTest {
#Test
public void test(){
boolean pass = false;
try {
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
String label = rs.getMetaData().getColumnLabel(1); // What do you get?
System.out.println("label = " + label);
while (rs.next()){
System.out.println(rs.getInt("d.deptId"));
pass = true;
}
} catch (SQLException e) {
e.printStackTrace();
pass=false;
}
assertTrue(pass);
}
#Test
public void test2(){
boolean pass = false;
try {
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("deptId"));
pass = true;
}
} catch (SQLException e) {
e.printStackTrace();
pass=false;
}
assertTrue(pass);
}
}
public class DbConn {
private static String url = "jdbc:postgresql://server:port/schema";
private static Properties props = new Properties(); {
props.setProperty("user","userid");
props.setProperty("password","passwprd");
}
private Connection conn;
private DbConn(){}
private static DbConn instance;
public static DbConn getInstance() throws SQLException{
if (instance == null){
instance = new DbConn();
instance.conn = DriverManager.getConnection(url, props);
}
return instance;
}
public ResultSet doQuery(String query) throws SQLException{
Logger.log("DbConn.doQuery: " + query);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
}
}
}
The query:
select d.deptId from Depts d
produces a single-column resultset with the result-alias "deptId". There is no "d.deptId" column. If you want one, you can request that as the column alias instead:
select d.deptId AS "d.deptId" from Depts d
PgJDBC can't do anything about this because it has no idea that the resultset column "deptId" is related to the "d.deptId" in the select-list. Teaching it about that would force it to understand way more about the SQL it processes than would be desirable, and lead to maintenance and performance challenges.
The second one works - why isn't that acceptable?
You can also do this:
System.out.println(rs.getInt(1));
If you change the query you have to change the code, too.