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.
Related
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?
I am new to JDBC and using a tutorial to create my first connection. However, I am getting the below error -
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
import java.sql.*;
public class Demo {
public static void main(String[] args) throws Exception {
String url="jdbc:mysql://localhost:3306//demo";
String user="root";
String password="vishal123";
String query = "select * from student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("user_name");
System.out.println(name);
st.close();
con.close();
}
}
Do let me know if you need any more details to solve the problem.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getOracleConnection();
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement();
//only for Oracle
rs = stmt.executeQuery("select object_name from user_objects where object_type = 'TABLE'");
while (rs.next()) {
String tableName = rs.getString(1);
System.out.println("tableName=" + tableName);
}
stmt.close();
conn.close();
}
/*private static Connection getHSQLConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}*/
/* public static Connection getMySqlConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/demo2s";
String username = "oost";
String password = "oost";
*/
/* Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
*/
public static Connection getOracleConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:Test";
String username = "system";
String password = "root12345";
Class.forName(driver); // load Oracle driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
I'm going to get the list of tables from Test database but I'm getting the error like listener refused connection, Listener refused the connection with the following error as:
ORA-12505, TNS: listener does not currently know of SID given in connect descriptor
But when I change Test to Orcl then its working fine but I want to select the table from particular Database.
Where did I go wrong?
Best way to solve problem is first read the error or exception you got
ORA-12505, TNS: listener does not currently know of SID
In this error SID means In short the unique name of your DB.
When you're changing it test it simply means it does not available on current DB url
or that SID(DB) does not exists you need to create new with same name
or if SID is available then check your URL for that SID
edit 1:
To find SID you can use select * from global_name;
it will give you one value use it as it is .
I think you need to use test.world
make this changes to url
String url = "jdbc:oracle:thin:#localhost:1521/Test";
or
String url = "jdbc:oracle:thin:#localhost:1521/Test.world";
I am working in command prompt this is my code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnf) {
System.out.println("Driver could not be loaded: " + cnf);
}
}
public static void main(String[] args)
{
String connectionUrl = "jdbc:mysql://localhost:3306/mysql";
String dbUser = "root";
String dbPwd = "admin";
Connection conn;
ResultSet rs;
String queryString = "SELECT ID, NAME FROM exptable";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();
// INSERT A RECORD
stmt.executeUpdate("INSERT INTO exptable (name) VALUES (\"TINU K\")");
// SELECT ALL RECORDS FROM EXPTABLE
rs = stmt.executeQuery(queryString);
System.out.println("ID \tNAME");
System.out.println("============");
while (rs.next()) {
System.out.print(rs.getInt("id") + ".\t" + rs.getString("name"));
System.out.println();
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}
i am getting error like
java.lang.ClassNotFoundException and java.sql.SQLException
so may i know what mistake have i made
You might have missed the classpath in your java command. While executing from command prompt you must mention the class path along with your command.
java -cp
ex:
java -cp /home/test/jars:/home/test/src com.test.Lab
I use Netbeans, doing a java app. I created a class ConnectDB for db connetion using Java DB in netbeans. i started the server and ten conneted to db. when i run the file it produce
java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver # 25 line
and
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/Libraryprj;create=true
#30 th line of code
the code is below
package Lms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
/**
*
* #author JOJO
*/
public class ConnectDB {
static Connection conn;
public static void main(String[] args) {
String driver = "org.apache.derby.jdbc.ClientDriver";
String connectionURL = "jdbc:derby://localhost:1527/Libraryprj;create=true";
String createString = "CREATE TABLE Employee (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)";
try {
Class.forName(driver);
} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(connectionURL);
Statement stmt = (Statement) conn.createStatement();
stmt.executeUpdate(createString);
PreparedStatement psInsert = conn.prepareStatement("insert into Employee values (?,?)");
psInsert.setString(1, args[0]);
psInsert.setString(2, args[1]);
psInsert.executeUpdate();
Statement stmt2 = (Statement) conn.createStatement();
ResultSet rs = stmt2.executeQuery("select * from Employee");
int num = 0;
while (rs.next()) {
System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address" + rs.getString(2));
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
get this library
http://repo.maven.apache.org/maven2/org/apache/derby/derbyclient/10.9.1.0/derbyclient-10.9.1.0.jar
and copy it to Derby's libs folder.
If you use Tomcat download derbyclient.jar from here . And copy the jar file to Tomcat's lib folder.