SQLException Handling - jdbc

I am trying to run a simple Java program which fetches data from the oracle database and display it. I connected the oracle database. Here is my code:
DataHandler Class:
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import oracle.jdbc.pool.OracleDataSource;
public class DataHandler {
public DataHandler() {
super();
}
String jdbcUrl = "jdbc:oracle:thin:#localhost:1521:ORCL";
//I already added the above line but still getting error.
String userid = "scott";
String password = "tiger";
Connection conn;
public void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setUser(jdbcUrl);
conn = ds.getConnection(userid,password);
}
Statement stmt;
ResultSet rset;
String query;
String sqlString;
public ResultSet getAllEmployees() throws SQLException{
getDBConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
query = "SELECT * FROM emp ORDER BY empno";
System.out.println("\nExecuting query: " + query);
rset = stmt.executeQuery(query);
return rset;
}
}
and the JavaClient Class as
JavaCLient CLass:
import java.sql.ResultSet;
public class JavaClient {
public JavaClient() {
super();
}
public static void main(String[] args) throws Exception{
DataHandler datahandler = new DataHandler();
ResultSet rset = datahandler.getAllEmployees();
while (rset.next()) {
System.out.println(rset.getInt(1) + " " +
rset.getString(2) + " " +
rset.getString(3) + " " +
rset.getString(4));
}
}
}
I get no compilation error but while running it I get following exception error
Error:
Exception in thread "main" java.sql.SQLException: Invalid Oracle URL specified: OracleDataSource.makeURL
at oracle.jdbc.pool.OracleDataSource.makeURL(OracleDataSource.java:1277)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:185)
at student_attendence_iem.DataHandler.getDBConnection(DataHandler.java:22)
at student_attendence_iem.DataHandler.getAllEmployees(DataHandler.java:31)
at student_attendence_iem.JavaClient.main(JavaClient.java:9)
Process exited with exit code 1.
Please help me. Thanks in advance. :)

You have not set URL of your database.
Add setURL(url) method which takes URL of database as parameter. Below is the code.
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(jdbcUrl);
Also, with ds.setUser(jdbcUrl); you are trying to setUser with the URL of database which is wrong.
You don't have to setUser like this as you are already doing that in the following line of code conn = ds.getConnection(userid,password);

Related

while inserting values in a table through JDBC java.lang.ArrayIndexOutOfBoundsException:

getting this error for the below code
java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at oracle.jdbc.driver.OracleSql.main(OracleSql.java:1717)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Z1 {
public static void main(String[] args) throws Exception
{
// String query = "select * from Employee";
//String sql = "CREATE TABLE people(\r\n"+ "id INT NOT NULL PRIMARY KEY,\r\n"+ "name VARCHAR2(50) \r\n"+ ");";
Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:","system","palak");
Statement stmt = con.createStatement();
String sql = "insert into test1 values(100)";
stmt.execute(sql);
System.out.println("dOne");
}
}

Find count of rows with empty value in Hbase

I have populated a Hbase table with rowid and vrious information pertaining to tweet such as clean-text,url,hashtag etc. as follows
902221655086211073 column=clean-tweet:clean-text-cta, timestamp=1514793745304, value=democrat mayor order hurricane harvey stand houston
However while populating I noticed that the some of the rows are empty like
902487280543305728 column=clean-tweet:clean-text-cta, timestamp=1514622371008, value=
Now how do I find the count of rows that are having data?
Please help me in this
There is no provision to do this in HBase shell as of now. May be you can use a simple code like this to get a number of records with no value for the provided column qualifier.
CountAndFilter [tableName] [columnFamily] [columnQualifier]
import java.io.IOException;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
public class CountAndFilter {
private static Connection conn;
private static int recordsWithoutValue = 0;
public static Admin getConnection() throws IOException {
if (conn == null) {
conn = ConnectionFactory.createConnection(HBaseConfiguration.create());
}
return conn.getAdmin();
}
public static void main(String args[]) throws IOException {
getConnection();
scan(args[0], args[1], args[2]);
System.out.println("Records with empty value : " + recordsWithoutValue);
}
public static void scan(String tableName, String columnFamily, String columnQualifier) throws IOException {
Table table = conn.getTable(TableName.valueOf(tableName));
ResultScanner rs = table.getScanner(new Scan().addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnQualifier)));
Result res = null;
try {
while ((res = rs.next()) != null) {
if (res.containsEmptyColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnQualifier))){
recordsWithoutValue++;
}
}
} finally {
rs.close();
}
}
}

Hive to Hbase comparision of data in tables

I am into DW testing and need to compare data from source to target.Source data is stored in hive/RDBMS while the target data is loaded in Hbase. I am new to Hbase .Can any one help me with the approach that i can take. What I am looking for is a similar function as that of "MINUS" . Is it possible ?
You should write java file in that you can combine:
HBase:
import java.io.IOException;
// HBASE
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
public class RetriveData{
public static void main(String[] args) throws IOException, Exception{
// Instantiating Configuration class
Configuration config = HBaseConfiguration.create();
// Instantiating HTable class
HTable table = new HTable(config, "emp");
// Instantiating Get class
Get g = new Get(Bytes.toBytes("row1"));
// Reading the data
Result result = table.get(g);
// Reading values from Result class object
byte [] value = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("name"));
byte [] value1 = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("city"));
// Printing the values
String name = Bytes.toString(value);
String city = Bytes.toString(value1);
**// CALL THE HIVE CLASS(HiveQLOrderBy)...YOU CAN COMPARE**
System.out.println("name: " + name + " city: " + city);
}
}
//HIVE
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveQLOrderBy {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
// Register driver and create driver instance
Class.forName(driverName);
// get connection
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", "");
// create statement
Statement stmt = con.createStatement();
// execute statement
Resultset res = stmt.executeQuery("SELECT * FROM employee ORDER BY DEPT;");
System.out.println(" ID \t Name \t Salary \t Designation \t Dept ");
while (res.next()) {
System.out.println(res.getInt(1) + " " + res.getString(2) + " " + res.getDouble(3) + " " + res.getString(4) + " " + res.getString(5));
}
con.close();
}
}

How to show Oracle DB Tables on my JDeveloper Swing projects frame?

I want to show my Oracle DB tables on my application. I create a new database connection DBConnection1. But I don't bind DBConnection1 in my class. How to do it?
OK. I solve my question.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection connection = DriverManager.getConnection(connStr,"scott","tiger");
Connector conn = new Connector(connStr);
Statement stmt = conn.getConnection().createStatement();
ResultSet rset = stmt.executeQuery(sql);
ResultSetMetaData metaData = rset.getMetaData();
int rowCount = metaData.getColumnCount();
for(i=1;i<=rowCount;i++)
headers.add(metaData.getColumnLabel(i).toString());
while(rset.next()){
Vector tmp = new Vector();
for(i=1;i<=rowCount;i++) {
tmp.add(rset.getString(i));
}
lists.add(tmp);
index++;
Here is the my connector class.
package client;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connector
{
private String connection_string;
private Statement stmt;
private Connection connection;
public Connector(String conn)
{
//String connection_string = "jdbc:oracle:thin:#<host>:<port>:<db name>";
try
{
connection_string = conn;
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection(conn,"scott","tiger");
} catch(Exception f)
{
f.printStackTrace();
}
}
public ResultSet execute(String sql)
{
try
{
stmt = connection.createStatement();
return stmt.executeQuery(sql);
} catch (Exception f)
{
f.printStackTrace();
}
return null;
}
public void setConnection_string(String connection_string)
{
this.connection_string = connection_string;
}
public String getConnection_string()
{
return connection_string;
}
public void setStmt(Statement stmt)
{
this.stmt = stmt;
}
public Statement getStmt()
{
return stmt;
}
public void setConnection(Connection connection)
{
this.connection = connection;
}
public Connection getConnection()
{
return connection;
}
}

JDBC connectivity issue

I'm using the NetBeans IDE(6.8). I have a DB class :
package garits;
import java.io.Serializable;
import java.sql.*;
import java.util.Properties;
public class DB implements Serializable{
private static final long serialVersionUID = 1L;
String dbURL = "jdbc:mysql:///team_project";
String user = "root";
String pwd = "arsenal";
String dbDriver = "com.mysql.jdbc.Driver";
private Connection dbCon;
private ResultSet r;
private Statement s;
public DB()
{}
public boolean connect() throws ClassNotFoundException,SQLException{
Class.forName(dbDriver);
Properties props = new Properties();
props.put(user, "root");
props.put(pwd, "arsenal");
props.put("charSet", "UTF-8");
props.put("lc_ctype", "UTF-8");
dbCon = DriverManager.getConnection(dbURL,props);
//dbCon = DriverManager.getConnection(dbURL,user,pwd);
return true;
}
public void close() throws SQLException{
dbCon.close();
if(r!=null)
r.close();
if(s!=null)
s.close();
}
public ResultSet execSQL(String sql) throws SQLException{
s = dbCon.createStatement();
r = s.executeQuery(sql);
return (r == null) ? null : r;
}
public int updateSQL(String sql) throws SQLException{
s = dbCon.createStatement();
int r = s.executeUpdate(sql);
return (r == 0) ? 0 : r;
}
public int updateSQL(String sql, String getID) throws SQLException{
s = dbCon.createStatement();
int autoIncValue = -1;
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
if (rs.next()) {
autoIncValue = rs.getInt(1);
}
return autoIncValue;
}
}
The jar file is im my library, but whenever I try to connect:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String result ="";
DB db = new DB();
try{
db.connect();
String query = "Select Role From User_Account Where Username=jTextField1.getText()AND Where Password=jTextField2.getText(); ";
ResultSet rs=db.execSQL(query);
while(rs.next())
{
result = rs.getString("Role");
}
if(result.equals(""))
{
JOptionPane.showMessageDialog(loginButton,"Access denied","Error Message",JOptionPane.ERROR_MESSAGE);
}
else if(result.equals("Administrator"))
{
MainPage_Admin admin = new MainPage_Admin();
}
}
catch(Exception e)
{
System.out.println("An error has occurred");
}
}
I get an error(the exception is caught)-the name of the database is "team_project" and password is "arsenal"-any ideas appreciated. I'm new to JDBC.
First step: use at least e.printStackTrace() in your catch-block to get some information from the exception. Otherwise you'll just be guessing.
MySQL database url connection property is wrong
jdbc:mysql://localhost:3306/<your database name>
instead of you are giving
jdbc:mysql:///team_project
modify and execute the program and better to handle the exception within the try/catch block instead of throws.

Resources