I was trying to have snowflake db connection using oracle Java stored procedure. But it's giving me error
ORA-29532: Java call terminated by uncaught Java exception: java.sql.SQLException: No suitable driver found
I have already downloaded snowflake-jdbc-3.6.19-javadoc.jar from related source.
Below is sample code of java class which will be called from oracle java procedure.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class SnowflakeDriverExample
{
public static void testdata() throws Exception
// public static void main(String[] args) throws Exception
{
// get connection
System.out.println("Create JDBC connection");
Connection connection = getConnection();
System.out.println("Done creating JDBC connectionn");
// create statement
System.out.println("Create JDBC statement");
Statement statement = connection.createStatement();
System.out.println("Done creating JDBC statementn");
// query the data
System.out.println("Query demo");
ResultSet resultSet = statement.executeQuery("SELECT DATA_ID FROM TEMP_TABLE");
System.out.println("Metadata:");
System.out.println("================================");
// fetch metadata
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
System.out.println("Number of columns=" +
resultSetMetaData.getColumnCount());
statement.close();
}
private static Connection getConnection()
throws SQLException
{
try
{
Class.forName("net.snowflake.client.jdbc.SnowflakeDriver");
}
catch (ClassNotFoundException ex)
{
System.err.println("Driver not found");
}
// Class.forName("net.snowflake.client.jdbc.SnowflakeDriver");
// build connection properties
Properties properties = new Properties();
properties.put("user", "XXX"); // replace "" with your username
properties.put("password", "XXXX"); // replace "" with your password
properties.put("account", "XXXX"); // replace "" with your account name
properties.put("db", "db1"); // replace "" with target database name
properties.put("schema", "MYSCHEMA"); // replace "" with target schema name
//properties.put("tracing", "on");
// create a new connection
String connectStr = null;//System.getenv("SF_JDBC_CONNECT_STRING");
// use the default connection string if it is not set in environment
if(connectStr == null)
{
connectStr = "jdbc:snowflake:XXXX"; // replace accountName with your account name
}
return DriverManager.getConnection(connectStr, properties);
}
}
How to import/integrate this driver for java stored procedure?
Related
I am very new to Java and am simply trying to connect to my MSSQL database and return a list of customers. When I try the JDBC connection, I get a "no suitable driver found" error. When I add a Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") statement, I get a ClassNotFound error. This seems like it should be a lot easier than it's turning out to be. Please help me either find a suitable driver or how to get access through the Class.forName usage.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConn {
public static String getConnString(){
return "jdbc:sqlserver://localhost\\SQLEXPRESS:1433;database=OhHold;";
}
public static void getConnection() {
try
{
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String user = "<USER>";
String pw = "****************";
Connection connection = DriverManager.getConnection(getConnString(), user, pw);
Statement statement = connection.createStatement();
String sql = "select txtCompanyName as company from tblCustomers where intNotActive <> 1";
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
System.out.println(result.getString(1));
}
}
/*
// Handle any errors that may have occurred.
catch (ClassNotFoundException e) {
e.printStackTrace();
}
*/
catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
getConnection();
}
}
I am using ojdbc8 12.2.0.1 in my maven project and I want to notify when there is a new entry in a table.
I was using ojdbc7 11.2.0.1 and oracle 11g and on that, it was working fine.
Now I am upgrading to oracle 12c for which I am using ojdbc8 12.2.0.1 jar.
The table is getting in the user_change_notification_regs table as I can see it but as soon as there is a new entry in the registered table, the registered table getting unregistered.
This means there is no entry in the user_change_notification_regs table.
The code is not giving any type of exception or error.
Any alternative of DCN would also help.
Code:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;
import oracle.jdbc.OracleStatement;
import oracle.jdbc.dcn.DatabaseChangeEvent;
import oracle.jdbc.dcn.DatabaseChangeListener;
import oracle.jdbc.dcn.DatabaseChangeRegistration;
public class DBChangeNotification {
public static void main(String[] argv) {
try {
Connection con = DriverManager.getConnection(url, user, password);
startDcn(con);
} catch (SQLException mainSQLException) {
mainSQLException.printStackTrace();
}
}
public static void startDcn(Connection conn) throws SQLException {
Properties prop = new Properties();
prop.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS, "true");
prop.setProperty(OracleConnection.DCN_IGNORE_DELETEOP, "true");
prop.setProperty(OracleConnection.DCN_IGNORE_UPDATEOP, "true");
DatabaseChangeRegistration dcr = conn.registerDatabaseChangeNotification(prop);
//listener not getting called as table getting unregistered.
dcr.addListener(new DatabaseChangeListener() {
public void onDatabaseChangeNotification(DatabaseChangeEvent dce) {
RowChangeDescription[] rowChangeDescription = dce.getTableChangeDescription()[0].getRowChangeDescription();
for (RowChangeDescription rcd: rowChangeDescription) {
System.out.print("Working"); //not getting print
}
}
});
Statement stmt = conn.createStatement();
((OracleStatement) stmt).setDatabaseChangeRegistration(dcr);
ResultSet rs = stmt.executeQuery("select * from demo where rownum='1' ");
while (rs.next()) {}
String[] tableNames = dcr.getTables();
for (int i = 0; i < tableNames.length; i++)
System.out.println(tableNames[i] + " is part of the registration.");
rs.close();
stmt.close();
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
Note: kindly ignore syntax error if any.
I am writing some archiving program in Java using derby DB. My program and DB connections (creating table, inserting and selecting data etc.) working fine when i use default user "APP" of Derby now.
When i try add some users and changing DB Properties, i can't connect to Database. I am sharing my User Creating and Changing DB Properties class below;
Creating user and Setting DB Properties:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateUser {
public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String connectionUrl = "jdbc:derby:sampleDB;user=APP;password=APP";
Connection con = null;
Statement stmt = null;
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.connection.requireAuthentication', 'true')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.authentication.provider', 'BUILTIN')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.user.testuser', 'ajaxj3x9')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.fullAccessUsers', 'testuser')");
stmt.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.propertiesOnly', 'false')");
stmt.close();
con.close();
boolean gotSQLExc = false;
try {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
} catch (SQLException se) {
if ( se.getSQLState().equals("XJ015") ) {
gotSQLExc = true;
}
}
if (!gotSQLExc) {
System.out.println("Database did not shut down normally");
} else {
System.out.println("Database shut down normally");
}
}
}
After that when i use below statement to connect DB i receive java.sql.SQLSyntaxErrorException: Schema 'TESTUSER' does not exist error
java.sql.Statement stmt = null;
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String connectionUrl = "jdbc:derby:sampleDB;create=false;user=testuser;password=ajaxj3x9";
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
Also i have tried CREATE SCHEMA AUTHORIZATION testuser after all creating and properties defined in CreateUser class (sure i have rollback first creation proccess before trying this and run same Creating process after adding this line) but when i try same statement i receive TESTTABLE Schema Not Exist error this time.
I am trying to create a hive table using java.
Here is my code:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveCreateTable {
private static String driverName = "com.facebook.presto.jdbc.PrestoDriver";
public static void main(String[] args) throws SQLException {
// Register driver and create driver instance
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("haiiiiii");
Connection con = DriverManager.getConnection("jdbc:presto://192.168.1.100:8023", "", "");
con.setCatalog("hive");
con.setSchema("log");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("create table access_log (c_ip varchar,cs_username varchar,cs_computername varchar,cs_date varchar,cs_code varchar,cs_method varchar,cs_uri_stem varchar,cs_uri_query varchar,cs_status_code varchar,cs_bytes varchar) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\b'LINES TERMINATED BY '\n'STORED AS TEXTFILE");
System.out.println("Table access_log4 created.");
ResultSet res1 = stmt.executeQuery("LOAD DATA LOCAL INPATH '/home/hadoop/access_log.txt'" + "OVERWRITE INTO TABLE access_log4;");
System.out.println("data loaded to access_log4.");
con.close();
}
}
and getting following error:
Exception in thread "main" java.sql.SQLException: Query failed
(#20150805_063004_00002_3dvaz): line 1:214: mismatched input 'ROW'
expecting
If we remove "ROW FORMAT DELIMITED FIELDS TERMINATED BY '\b'LINES TERMINATED BY '\n'STORED AS TEXTFILE" table is creating but data is not loaded.
For an Oracle database, the following program will throw SQL exceptions only for some threads. Why downgrading resultSetConcurrency from CONCUR_UPDATABLE to CONCUR_READ_ONLY? In a single thread environment this is not happening.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main extends Thread {
public static final String DBURL = "jdbc:oracle:thin:#localhost:1521:DB";
public static final String DBUSER = "USER";
public static final String DBPASS = "PASS";
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0; i<20; i++)
new Main().start();
}
#Override
public void run() {
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
con.setAutoCommit(false);
try(PreparedStatement pstmt = con.prepareStatement("SELECT COLUMN1 FROM TABLE1 FOR UPDATE NOWAIT",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE))
{
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.updateString(1, "12345");
rs.updateRow();
}
}
finally
{
con.commit();
con.close();
}
}
catch(SQLException e)
{
if(!e.toString().contains("NOWAIT"))
e.printStackTrace();
}
}
}
You can look at the warnings raised against the result set/statement/connection to see why it was downgraded. With this added after the executeQuery() call:
SQLWarning warning = pstmt.getWarnings();
while (warning != null)
{
System.out.println("Warning: " + warning.getSQLState()
+ ": " + warning.getErrorCode());
System.out.println(warning.getMessage());
warning = warning.getNextWarning();
}
In this case you'll sometimes see:
Warning: 99999: 17091
Warning: Unable to create resultset at the requested type and/or concurrency level: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired
You're looking for a NOWAIT exception, but you're getting a warning. What isn't clear to me is why you still get a result set in that scenario; but you can at least trap that warning and not go into the result set loop if you see it.