Doesn't match table_names jdbc program showing result and sql showing result - oracle

My jdbc program code
package table;
import java.sql.*;
public class sdfjksjk {
static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
static final String DB_URL = "jdbc:oracle:thin:#192.168.1.12:1521:aftdb";
static final String USER = "system";
static final String PASS = "manager";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.
getTables(null, "SYSTEM", "%", null);
while (rs.next())
{
System.out.println(rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
this code showing 231 table name,but in my sql developer select table_name from user_tables it showing 207 table names. What is the wrong in my program?

The last parameter of md.getTables is a list of table types.
You supply the value null which lists all table types ("TABLE", "VIEW" and possibly other types).
In sql developer you are just seeing regular tables (not views).
Edit:
Make the call like this to just get regular tables:
String regularTables[] = new String[] {"TABLE"};
ResultSet rs = md.
getTables(null, "SYSTEM", "%", regularTables);

Related

Getting ambiguous result using JDBC Metadata API for Hive

I am trying to get Table names for hive using DatabaseMetaData in a similar way like RDBMS.
Sample code:
try (Connection con = getJdbcConnection(connectionUri, driverName, username, password);) {
DatabaseMetaData metadata = con.getMetaData();
ResultSet rs = metadata.getTables(null, null, tableName, null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
} catch (SQLException e) {
}
private static void registerDriver(String driverName) {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
LOG.error("No class found for " + driverName + ". Details: " + e);
}
}
private static Connection getJdbcConnection(String connectionUri, String driverName, String username,
String password) throws SQLException{
registerDriver(driverName);
return DriverManager.getConnection(connectionUri, username,password);
}
There is no table in a particular database. Using different different table names, I am getting different output.
For example:
I put table name emp, there are 3 records with name emp
I put table name employee, there are 5 records with name employee
I put table name emp12, it is returning no records (which is expected)
Am I doing something wrong?
Shouldn't I use DatabaseMetaData for checking table existence?
I need to pass schema name in getTables method
Signature:
ResultSet getTables(String catalog,
String schemaPattern,
String tableNamePattern,
String[] types)
throws SQLException
I passed following agruments:
catalog = null;
schemaPattern = Hive schema Name
tableNamePattern = Hive Table Name
types = new String[] { "TABLE" }
Sample code:
try (Connection con = getJdbcConnection(connectionUri, driverName, username, password);) {
DatabaseMetaData metadata = con.getMetaData();
ResultSet rs = metadata.getTables(null, schemaName, tableName, new String[] { "TABLE" });
while (rs.next()) {
String tName = rs.getString("TABLE_NAME");
if (tName != null && tName.equals(tableName)) {
LOG.info("Table [" + tableName + "] is present in the Database.");
return true;
}
}
rs.close();
LOG.info("Table [" + tableName + "] is not present in the Database.");
return false;
} catch (SQLException e) {
LOG.error("Not able to get Table Metadata . Caused By: " + e);
}

ResultSet next() is returning only one row

I am having this method
public List<Course> getCourses() throws InvalidCourseDataException {
ArrayList<Course> allCoursesFromDB = new ArrayList<>();
Connection dbConnection = null;
String getFromTableSQL = "SELECT * FROM courses";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
resultSet = statement.executeQuery(getFromTableSQL);
while (resultSet.next()) {
String courseCategory = resultSet.getString("course_category");
String courseTitle = resultSet.getString("course_title");
int courseId = resultSet.getInt("course_id");
Date startDate = resultSet.getTimestamp("starting_date");
Date endDate = resultSet.getDate("ending_date");
String description = resultSet.getString("description");
int teacherId = resultSet.getInt("teacher_id");
Course course = new Course(courseCategory, courseTitle, startDate, endDate);
course.setCourseId(courseId);
course.setTeacherId(teacherId);
course.setDescription(description);
addParticipantsIdToCourse(course);
allCoursesFromDB.add(course);
}
The getDBConnection() method is
private static Connection getDBConnection() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
My problem is that resultSet.next() is returning only the first row from DB. I'am sure that I have multiple rows. I saw JDBC ResultSet is giving only one row although there are many rows in table? that question but it really doesn't answer my :)
I am sorry for the question. I found my mistake. ResultSet next() method is working fine, but I've changed its value in my addParticipantsIdToCourse(course) method :)

Hive "ANALYZE TABLE" how to execute from java

I need to compute the number of rows in a hive table, for that
I am using the query:
ANALYZE TABLE p_7 COMPUTE STATISTICS noscan
I want to fetch the results through java, I am trying with the below
code and have no luck. the error I get is :
Exception in thread "main" java.sql.SQLException: The query did not generate a result set!
at org.apache.hive.jdbc.HiveStatement.executeQuery(HiveStatement.java:393)
at HiveJdbcClient.main(HiveJdbcClient.java:22)
code I am using is :
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveJdbcClient {
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "hive", "");
System.out.println("connected");
Statement statement = con.createStatement();
String query = "ANALYZE TABLE p_7 COMPUTE STATISTICS noscan";
ResultSet res = statement.executeQuery(query);
}
}
I dont know how to execute a query such as:
ANALYZE TABLE p_7 COMPUTE STATISTICS noscan
through java. Any help on this would be of great help to me. Thanks.
Use the ANALYZE TABLE statement without 'NOSCAN' to compute the number of rows.
Note: This statement does not produce resultSet object.
To fetch the stored stats, use the following statement.
DESCRIBE FORMATTED tableName
In the output, the number of rows is listed in parameters array. Use regex to extract it.
Here is the sample code:
String analyzeQuery = "ANALYZE TABLE p_7 COMPUTE STATISTICS";
String describeQuery = "DESCRIBE FORMATTED p_7";
stmt.execute(analyzeQuery);
StringBuilder sb = new StringBuilder();
try (ResultSet rs = stmt.executeQuery(describeQuery)) {
while (rs.next()) {
int count = rs.getMetaData().getColumnCount();
for (int j = 1; j <= count; j++) {
sb.append(rs.getString(j));
}
}
}
System.out.println("Output: "+ sb.toString());
Refer https://cwiki.apache.org/confluence/display/Hive/StatsDev for details on Table and Partition statistics.
Try the below code for getting number of rows of a table:
public static Connection createConnection(String hive_ip)
{
String hive_url="jdbc:hive2://"+hive_ip;
Connection con=null;
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
System.out.println(hive_url+"/");
con = DriverManager.getConnection(
hive_url+"/",
hive_username,hive_password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static int getHiveColumnRowCount(String tablename,String db_name)
{
int count=0;
Connection con=createConnection();
try {
Statement st=con.createStatement();
int i=0;
String count_query="show tblproperties "+db_name+"."+tablename;
ResultSet rs=st.executeQuery(count_query);
while(rs.next())
{
i++;
if(i==3)
{
count=Integer.parseInt(rs.getString(2));
}
}
System.out.println("COUNT:"+count);
rs.close();
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
Hope it helps :)

JDBC Update on Oracle failed to commit

I have JDBC Dao Object, and used PreparedStatements to do UPDATE a row at a table in my DB.
I have other methods such as SELECT and INSERT which are successful (insert-commit works).
But the update, just does not commit the changes (does not work at all). While the same UPDATE statement works from Oracle SQLServer directly.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StaffDAO {
private Connection conn;
public StaffDAO() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Oracle Driver not found");
System.exit(0);
}
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#db01.xxxdev.com:1521:training",
"training", "training");
} catch (SQLException e) {
System.out.println("Driver manager failed");
}
}
public ResultSet getAllResultSet() {
String sql = "select * from ben_staff";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
return rs;
}
public Staff viewEmployee(String id) throws Exception {
Staff st = new Staff();
String sql = "SELECT * from BEN_STAFF where BEN_STAFF.id =\'" + id
+ "\'";
// String psql = "SELECT * FROM BEN_STAFF WHERE ID = ?";
Statement statement = null;
// PreparedStatement pstatement = null;
try {
statement = conn.createStatement();
// pstatement = conn.prepareStatement(psql);
// pstatement.setString(1, id);
} catch (SQLException e) {
System.out.println("Create Statement failed");
System.exit(1);
}
ResultSet rs = null;
try {
rs = statement.executeQuery(sql);
// rs = pstatement.executeQuery();
while (rs.next()) {
st.setId(rs.getString("ID"));
st.setLastName(rs.getString("LASTNAME"));
st.setFirstName(rs.getString("FIRSTNAME"));
st.setMi(rs.getString("MI"));
st.setAddress(rs.getString("ADDRESS"));
st.setCity(rs.getString("CITY"));
st.setState(rs.getString("STATE"));
st.setTelephone(rs.getString("TELEPHONE"));
st.setEmail(rs.getString("EMAIL"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return st;
}
public boolean insert(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "insert into ben_staff (id, lastname, firstname, mi, address, city, state, telephone, email)"
+ "values (?,?,?,?,?,?,?,?,?)";
try {
pstmt = conn.prepareStatement(psql);
// pstmt.setString(1,st.getId());
// pstmt.setString(2, st.getLastName());
// pstmt.setString(3, st.getFirstName());
pstmt.setString(1, id);
pstmt.setString(2, last);
pstmt.setString(3, first);
pstmt.setString(4, mi);
pstmt.setString(5, address);
pstmt.setString(6, city);
pstmt.setString(7, state);
pstmt.setString(8, telephone);
pstmt.setString(9, email);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public boolean update(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "update ben_staff set lastname=?, firstname=?, mi=?, address=?, city=?, state=?,"
+ " telephone=?, email=? where id=?";
try {
pstmt = conn.prepareStatement(psql);
pstmt.setString(1, last);
pstmt.setString(2, first);
pstmt.setString(3, mi);
pstmt.setString(4, address);
pstmt.setString(5, city);
pstmt.setString(6, state);
pstmt.setString(7, telephone);
pstmt.setString(8, email);
pstmt.setString(9, id);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
try{
conn.rollback();
} catch (SQLException exx){
System.out.println("Update Rollback Failed");
}
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public void close() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What does pstmt.executeUpdate(); return? That would tell you how many rows are being updated. Something like
int numRows = pstmt.executeUpdate();
System.out.println( "Update modified " + numRows + " rows." );
My guess is that your update isn't actually modifying any rows. That would imply that the id being passed in was incorrect. Remember that string comparisons in SQL Server are case insensitive by default while they are case sensitive by default in Oracle.

How to Connect oracle db with JSP

I am a new for JSP and I dont know any information about connection of oracle with JSP can anyone help me step by step?
You have to look at JDBC for Oracle. Using Java of course, not JSP.
This is a very basic Database class I used to use for very little projects.
public class Database {
private String driverName = "oracle.jdbc.driver.OracleDriver";
private Connection conn;
public static Hashtable errors = null;
public Database(String serverName, String portNumber, String serviceName, String username, String password, String db) {
errors = new Hashtable();
try {
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + serviceName;
Class.forName(driverName);
this.conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.out.println(e);
errors.put(db, e);
}
}
public Connection getConnection(){
return this.conn;
}
}
here is a sample of a query
Database db = new Database(......); // see Database class construct
try {
java.sql.Statement st = db.getConnection().createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM FOO");
while(rs.next()){
// your code
}
rs.close();
st.close();
} catch (SQLException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
hope this helps :)

Resources