Difficulty getting PK in HSQLDB - java

I'm using hsqldb for a unit test (NOT production). These tests need to access the table's primary key, but I cant seem to get it to work. BTW, I'm using the latest version 2.0.0
I've created a small snippet to recreate the problem. Any feedback would be greatly appreciated
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static void main(String[] args) throws Exception {
Connection conn = getHSQLConnection();
System.out.println("Got Connection.");
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,name varchar (20), PRIMARY KEY (id) );");
ResultSet rs = null;
DatabaseMetaData meta = conn.getMetaData();
rs = meta.getPrimaryKeys(null, null, "survey");
String pk = null;
if (rs.next()) {
pk = rs.getString("COLUMN_NAME");
System.out.println("getPrimaryKeys(): columnName=" + pk);
}
else {
System.out.println("Couldn't get the PK");
}
st.close();
conn.close();
}
private static Connection getHSQLConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/test1";
return DriverManager.getConnection(url, "sa", "");
}
}

Use this:
rs = meta.getPrimaryKeys(null, null, "SURVEY");
In standard SQL, the name of a column, table or other object is turned into all uppercase unless you use double quotes around the name when you use it in SQL statements.
The latest version is currently 2.2.3 and has bug fixes and improvments over version 2.0.0

Related

Connect Oracle Java stored procedure to Snowflake

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?

Unable to get column name and column lable in sql server result set meta data

Can anybody help me to get actual column name and its alias using ResultSetMetaData by connecting to sqlserver database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
class MysqlCon {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=alcoa", "sa", "test");
Statement stmt = con.createStatement();
String query = "SELECT std_code as \"Student code\" from Student ";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsm =rs.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
System.out.println(rsm.getColumnLabel(i) + "--" + rsm.getColumnName(i));
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
output
Student code--Student code
Above code works as expected in other database like mysql and oracle.
I checked code for SQLServerResultSetMetaData. Both methods getColumnLabel and getColumnName are identical.
abzycdxw65, has raised same issue on their github account. it is closed.
Is there any way to get following output:
Student code--std_code
If I get your question you can try the followings to retrieve column names
select name from sys.columns

Table not found error in eclipse IDE, what to do?

I recently started working on JDBC and I got an Error as Table not found
Table TRIAL not found; SQL statement:
insert into trial values(1,'hello') [42102-73]
Here is my code, also I have already created a table in h2 DB
package trial1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Customer {
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:h2:~/test","Aziz", "password");
Statement st = conn.createStatement();
String str = "insert into trial values(1,'hello')";
st.execute(str);
System.out.println("Succes");
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Java Derby Creating User and "Schema Does Not Exist" Error

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.

java.lang.ClassNotFoundException Netbeans java derby

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.

Categories