Executing java program on redshift - java

For example I have coded the following php code and run on redshift like below.
<?php
$connect = pg_connect("host=xx.xxxx.us-east-1.redshift.amazonaws.com port=xxxx dbname=testdb user=xxxx password=xxxxxx");
$query = "select name, email from mytable LIMIT 7";
$result = pg_query($connect,$query);
while(($row = pg_fetch_array($result)) != null) {
$name = $row[0];
$email = $row[1];
echo $name." <<>> ".$email." <<>> ";
}
?>
I saved the above php file and executed in the below way.
myuser#ip-20-143-43-144:/home/myuser$ php runquery.php <Enter>
Then it gives me the output.
I want to test the same thing with java. So I took the example from the aws and saved in the same location.
public class ConnectToCluster {
static final String dbURL = "jdbc:postgresql://xxxx.xxxxx.us-east-1.redshift.amazonaws.com:xxxx/testdb";
static final String MasterUsername = "XXXX";
static final String MasterUserPassword = "XXXXXX";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Dynamically load postgresql driver at runtime.
Class.forName("org.postgresql.Driver");
//Open a connection and define properties.
System.out.println("Connecting to database...");
Properties props = new Properties();
//Uncomment the following line if using a keystore.
//props.setProperty("ssl", "true");
props.setProperty("user", MasterUsername);
props.setProperty("password", MasterUserPassword);
conn = DriverManager.getConnection(dbURL, props);
//Try a simple query.
System.out.println("Listing system tables...");
stmt = conn.createStatement();
String sql;
sql = "select * from information_schema.tables;";
ResultSet rs = stmt.executeQuery(sql);
//Get the data from the result set.
while(rs.next()){
//Retrieve two columns.
String catalog = rs.getString("table_catalog");
String name = rs.getString("table_name");
//Display values.
System.out.print("Catalog: " + catalog);
System.out.println(", Name: " + name);
}
rs.close();
stmt.close();
conn.close();
}catch(Exception ex){
//For convenience, handle all errors here.
ex.printStackTrace();
}finally{
//Finally block to close resources.
try{
if(stmt!=null)
stmt.close();
}catch(Exception ex){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
System.out.println("Finished connectivity test.");
}
}
I saved this .java file too in the same location. So, can someone please tell me how to run this java file on command as I did for php.

(1) Download a postgresql JDBC driver from the following link and put it in the same directory of ConnectToCluster.java.
http://jdbc.postgresql.org/download/postgresql-8.4-703.jdbc4.jar
(2) Add the missing lines(import java library) in the head of the java file.
import java.sql.*;
import java.util.*;
public class ConnectToCluster {
...
(3) Run the following command.
javac ConnectToCluster.java && java -cp .:postgresql-8.4-703.jdbc4.jar ConnectToCluster

Related

Flex - 'Cannot create class of type' error RemoteObject

I have the following Java class RemoteDBAccess inside validator package as follows. Basically, the function inside the class takes a string as an input and returns a string valid or invalid as output:
public class RemoteDBAccess {
public String Validator(String input)
{
String Output = "";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://ctovm1873.dev.spotlight.com:3306/ttds";
String connectionUser = "root";
String connectionPassword = "root";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
int rowcount = 0;
if(input.startsWith("CHG"))
{
rs = stmt.executeQuery("Select * from rm_projectrepository_gen where snow_change_id like '" + input + "'");
while (rs.next() != false) {
++rowcount;
}
}
else
{
rs = stmt.executeQuery("Select * from rm_projectrepository_gen where idRM_ProjectRepository_Gen like '" + input + "'");
while (rs.next() != false) {
++rowcount;
}
}
if(rowcount == 0)
{
Output = "invalid";
}
else{
Output = "valid";
}
}
catch (Exception e) {
e.printStackTrace();
}
return Output;
}
}
In the remoting-config.xml file, I have added the destination for my RemoteObject as follows:`
<destination id="RemoteDBAccess">
<properties>
<source>validator.RemoteDBAccess</source>
</properties>
<adapter ref="java-object"/>
</destination>
Inside my flex code, I have created the RemoteObject as follows:<mx:RemoteObject id="BeforeWithAfterValidator" destination="RemoteDBAccess" source="validator.RemoteDBAccess" result="Alert.show(event.result.toString());" fault="Alert.show(event.fault.faultString);"/>
Now, when I use the following piece of code to call the remote method:
var Data:String = "1239";
Alert.show(BeforeWithAfterValidator.Validator(Data));
The alert box displays: Cannot create class of type 'validator.RemoteDBAccess'.
Please help me with the issue.
I went inside the WEB-INF/classes folder of my Tomcat installation and created a folder named validator, inside which I put my RemoteDBAccess.class file(that justified the source for my RemoteObject(validator.RemoteDBAccess).
Afterwards, restarted the Tomcat server, re-built my flex code and it worked.

JDBC - Retrieving Resultset into a list

The aim of the code here is to Read a record by selecting a column.
I have following columns in the SQL DB.
------------------------------
|id | Topic | Comment | Time |
------------------------------
What I want to do is:-
Read the DB
Able to select rows by Topic
Show or Return the values of selected rows by Topic
The Topic could be duplicated, however the duplicated values should not been seen during the process of selection but the values of all column should be retrieved (as well as duplicated ones).
public class ReadRecordTopic{
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS?user=root&password=";
// Database credentials
//static final String USER = "username";
//static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement..." + "\n");
stmt = conn.createStatement();
String sql = "SELECT id, Topic, Comment, Time FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String Topic = (String) rs.getString("Topic");
String Comment = rs.getString("Comment");
String Time = rs.getString("Time");
String menu [] = Topic.split(",");
Object[] selectionValues = menu;
String initialSelection = "";
Object selection = JOptionPane.showInputDialog(null,
"Please select the Topic.", "Reseach Forum Menu",
JOptionPane.QUESTION_MESSAGE, null, selectionValues,
initialSelection);
String a = "Research Topic: " + Topic + "\n";
String b = "[" + Time + "]" + " Comment:" + Comment + "\n";
if(selection == Topic){JOptionPane.showMessageDialog(null, a + b);
}
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
1- Create Registration.class
public class Registration{
private int id;
private String topic;
...
...
...
//getters and setters
}
2- Change your sql and function name for what do yo want and use it.
//for order topic
String sql = SELECT id, Topic, Comment, Time FROM Registration order by topic.
//function for just spesific topic
public class ArrayList<Registration> getRegisWithTopic(String topicName){
String sql = SELECT id, Topic, Comment, Time FROM Registration order by topic WHERE TOpic = topicName ;
}
3- in while create new Registration.class and add to ArrayList and return this list
ArrayList<Registration> newList = new ArrayList<Registration>();
while(rs.next()){
Registration newReg = new Registration();
//Retrieve by column name
newReg.setId(rs.getInt("id"));
newReg.setTopic(rs.getString("Topic"));
...
...
...
//add this obj to list
newList.add(newReg);
}
return newList ;

Connecting MS Access Database with my project

I m trying to execute this code & it shows successfull execution but i cant get any value n access database file which i had create.
so, please find mistake in my code so that i can get some values in database table.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename ="D:\\Database for Mini Project\\Database21(example).mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Database for Mini Project\\Database21(example).mdb";
try (Connection con = DriverManager.getConnection( database ,"","")) {
Statement s = con.createStatement();
String b=request.getParameter("uname");
String c=request.getParameter("pass");
String query="insert into A.ABC1(uname,pass) values='"+b+"','"+c+"'";
s.executeQuery(query);
s.close();
change s.executeQuery(query); to s.executeUpdate(query);
For data manipulation language use executeQuery(); as mentioned in oracle docs
Try this
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename ="D:\\Database for Mini Project\\Database21(example).mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Database for Mini Project\\Database21(example).mdb";
String b=request.getParameter("uname");
String c=request.getParameter("pass");
try {
// connects to the database
Connection con = DriverManager.getConnection( database ,"","")) {
Statement s = con.createStatement();
String query="insert into A.ABC1(uname,pass) values(?,?);
PreparedStatement statement = conn.prepareStatement(query);
s.setString(1, b);
s.setString(2, c);
int row = s.executeUpdate();
if (row > 0) {
message = "Query executed";
}
} catch (SQLException ex) { //catch ur msaccess exception..I use mysql
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (con != null) {
// closes the database connection
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
I use mysql as my database..so wherever there is catch(SQLException ex) replace it with msaccess exception..

How to access the another system mysql database through java program?

How to access the another system mysql database through java program?Am using the following program but i have get the communication error?what are the changes are need to connect the another system mysql database?
Public void dbconnection() {
String name = "";
String port = "3306";
String user = "system";
String pass = "system";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
You're not creating an instance of the driver class:
Class.forName("com.mysql.jdbc.Driver").newInstance();
[update: not necessary after all, ignore that]
And you're also referencing "sun.jdbc.odbc.JdbcOdbcDriver", is that necessary? If so, shouldn't you instantiate it also? [update: probably not]
If it works with localhost, and not with the IP specified, you need to configure mysql to listen on all ports.
jcomeau#intrepid:/tmp$ cat dbconnection.java; javac dbconnection.java; sudo java -cp .:/usr/share/maven-repo/mysql/mysql-connector-java/5.1.16/mysql-connector-java-5.1.16.jar dbconnection
import java.sql.*;
public class dbconnection {
public static void main(String args[]) {
String name = "";
String port = "3306";
String user = "root";
String pass = "";
String dbname = "imagetagging";
String host="127.0.0.1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from taggers";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
URL:jdbc:mysql://127.0.0.1:3306/imagetagging
Name:1
Name:2
Name:3
Name:4
Name:5
Name:6
Name:7
Name:8
Name:9
Name:10
Name:11
Name:12
Name:13
Name:14
Name:15
Name:16
Name:17
Name:18
Name:19
Name:20
Name:21
As I understand you just need to specify another connection string, with another host and other credentials, e.g.:
...
String port = "3306";
String user = "user_name";
String pass = "password";
String dbname = "db_name";
String host="host_name";
...
You have to do 3(with 4th step optional) simple things to connect to your remote mysql database server.
Open up any GUI tool for mysql database management (your IDE, Mysql Workbench or smth else), check if you can connect to your database by specifying your credentials, host, port and database name.
If that succeeds you know there is nothing wrong on the db part (go to 3), if not, and you are sure you do everything correctly up to this point go to point 2.
check out this post on how to enable remote access to your db and try again (go to pkt 1)
You would have to clean up a bit your code, have a look into simple and to the point tutorial on how to connect and execute simple sql statements with java on Vogella tutorial
Once everything is working correctly, remember to give +1 on Vogella tutorial, praise the cybercity or any other website for the explanation on how to enable remote access on you db and don't forget to come back to stackoverflow and reward all good answers :)

DB query not populating to combo box...why?

I've been at this for awhile and have tried different examples (including a few that I found here), and tried to adapt them to what I need.
I am trying to use a DB query in a servlet to populate a combo box in the resulting html form that is created. While it all compiles and the page pops up with a combobox, there is nothing in the box to choose from, which tells me that something is wrong with how I am passing variables.
I've basically narrowed my methods down to two, but get the same results from both.
Can someone have a look-see and give me a clue?
out.print(`"<tr><td>SoldWhich Home ID: `</td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
ArrayList<String> soldWhich = new ArrayList<String>();
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String[])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
And the other method:
out.print(`"<tr><td>SoldWhich Home ID: </td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try{
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home ORDER BY home_id";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
soldWhich.add(rs1.getString(1));
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String [])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
Where are you setting "home_id" request attribute and why are you even setting it? I think you should take out the following line of code and see if it works. Modify your code to this.
List<String> soldWhich = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
I think you are not actually getting values (sh) in the "for(String sh : soldWhich)" loop. Can you try printing the values in a simple table just to see if you actually get data? Also why aren't you using jstl to perform this task? And your catch block does not log any errors either in case you are actually getting some sort of errors that will go unnoticed.

Categories