Java and Firebird Embedded how to create db? - java

now i get java.sql.SQLException: No suitable driver found for jdbc:firebirdsql:embedded:f/test.fdb
i included jaybird jars with my project. please help me out
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.firebirdsql.gds.impl.GDSType;
import org.firebirdsql.management.FBManager;
public class FireBirdCreator {
public FireBirdCreator() {
FBManager manager = new FBManager(GDSType.getType("EMBEDDED"));
try {
manager.start();
manager.createDatabase("f:/test.fdb", "sysdba", "masterkey");
manager.stop();
Connection bd = DriverManager.getConnection("jdbc:firebirdsql:embedded:f/test.fdb");
Statement st = bd.createStatement();
st.execute("create table if not exists 'TABLE1' ('name1' int, 'name2' text, 'name3' text);");
st.execute("insert into 'TABLE1' ('name1', 'name2', 'name3') values (1, 'name1', 'name2'); ");
st.execute("insert into 'TABLE1' ('name1', 'name2', 'name3') values (2, 'name3', 'name4'); ");
st.execute("insert into 'TABLE1' ('name1', 'name2', 'name3') values (3, 'name5', 'name6');");
ResultSet rs = st.executeQuery("select * from TABLE1");
while (rs.next())
{
System.out.print (rs.getString(1)+" ");
System.out.print (rs.getString(2)+" ");
System.out.println(rs.getString(3));
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
FireBirdCreator fbc = new FireBirdCreator();
}
}

The error message indicates that the file does not exist. The fact that it shows 'null' instead of the actual filename might be a mismatch between embedded version and Jaybird version.
To create a database you need to use the following code (and handle the exceptions it throws in a correct manner):
FBManager manager = new FBManager(GDSType.getType("EMBEDDED"));
manager.start();
manager.createDatabase("database.fdb", "", "");
manager.stop();
Also be aware that the DDL you are using to create the table is not valid Firebird SQL. You will need to use RECREATE TABLE and Firebird does not have a type called text.
Full disclosure: I am one of the developers of Jaybird (the Firebird JDBC driver).

Related

How to execute anonymous PL/SQL from Java using jdbctemplate

I want to call this query (which works when run on SQL developer) from Java
DECLARE
TYPE my_id_tab IS
TABLE OF my_table.my_id%TYPE;
my_ids my_id_tab;
BEGIN
UPDATE my_table
SET
another_id = NULL
WHERE
another_id IS NULL
AND create_datetime BETWEEN '03-JUN-19' AND '05-JUN-19'
RETURNING my_id BULK COLLECT INTO my_ids;
COMMIT;
END;
But I believe Java is having a tough time trying to figure out that I want the collection of my_ids returned to me.
Here's what I tried so far with exception messages like java.sql.SQLException: Invalid column index
or
java.sql.SQLException: operation not allowed: Ordinal binding and Named binding cannot be combined!
final Connection connection = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
try (final CallableStatement callableStatement = connection.prepareCall(TEST_SQL))
{
callableStatement.registerOutParameter("my_ids", Types.ARRAY);
callableStatement.executeUpdate();
int[] arr = (int[]) callableStatement.getArray("my_ids").getArray();
return Arrays.stream(arr).boxed().collect(Collectors.toSet());
}
catch (final SQLException e)
{
LOG.info("threw exception, {}", e);
}
finally
{
DataSourceUtils.releaseConnection(connection, jdbcTemplate.getDataSource());
}
It's not the simplest thing, but it's pretty easy to do. You will need to create a TYPE in Oracle to define the results.
For this demo, create and populate EMP and DEPT: EMP and DEPT script
Create the TYPE, needed to define the array that will be returned:
create type t_integer_array as table of integer;
We will be running the following UPDATE, which will update only a few rows:
UPDATE emp
SET job = job -- a nonsense update
WHERE comm IS NOT NULL -- only affect some of the rows
Here is the Java:
package test;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
import java.util.Arrays;
public class OracleTest {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"<your JDBC url>", "<your user>", "<your password>");
// Prepare the call, without defining the the output variable
// in a DECLARE section of the PL/SQL itself, you just need to
// include a "?" and then associate the correct type in the
// next step.
CallableStatement cs = conn.prepareCall(
"BEGIN\n"
+ " UPDATE emp\n"
+ " SET job = job\n"
+ " WHERE comm is not null\n"
+ " RETURNING empno BULK COLLECT INTO ?;\n"
+ "END;");
// Register the single OUT parameter as an array, using the
// type that was defined in the database, T_INTEGER_ARRAY.
cs.registerOutParameter(1, Types.ARRAY, "T_INTEGER_ARRAY");
cs.execute();
// Now get the array back, as array of BigDecimal.
// BigDecimal is used because it doesn't have precision
// problems like floating point, it will contain all digits
// that the database provided.
BigDecimal[] nums = (BigDecimal[]) (cs.getArray(1).getArray());
System.out.println(Arrays.toString(nums));
cs.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And here's my output:
[7499, 7521, 7654, 7844]
These are the technical keys (empno) for only the rows that were affected by the update.

How to fix table already created and values not showing up in console with SQL in Java?

I'm in a Java class and the assignment is to create a table that will show the first ten values of pre-selected columns. However, when I run my code, with the sql running the way it is it says that my table is already created. I was wondering if there was a way for it to stop erroring out when that happens and to still show my code? Also when I set up a new table, the values that I need, (Income, ID, Pep) won't show up, just the headers I established before the syntax will. How would I make these fixes so it stops erroring out and I see my values in the console log?
This is running in eclipse, extended with prior project files from the class i'm taking. I've tried adding prepared statements, attempted to parse for strings to other variables and attempted syntax to achieve the values I need.
LoanProccessing.java file (Main file):
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoanProcessing extends BankRecords {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
BankRecords br = new BankRecords();
br.readData();
Dao dao = new Dao();
dao.createTable();
dao.insertRecords(torbs); // perform inserts
ResultSet rs = dao.retrieveRecords();
System.out.println("ID\t\tINCOME\t\tPEP");
try {
while (rs.next()) {
String ID= rs.getString(2);
double income=rs.getDouble(3);
String pep=rs.getString(4);
System.out.println(ID + "\t" + income + "\t" + pep);
}
}
catch (SQLException e ) {
e.printStackTrace();
}
String s = "";
s=String.format("%10s\t %10s \t%10s \t%10s \t%10s \t%10s ", rs.getString(2), rs.getDouble(3), rs.getString(4));
System.out.println(s);
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println("Cur dt=" + timeStamp);
Dao.java file:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Dao {
//Declare DB objects
DBConnect conn = null;
Statement stmt = null;
// constructor
public Dao() { //create db object instance
conn = new DBConnect();
}
public void createTable() {
try {
// Open a connection
System.out.println("Connecting to a selected database to create Table...");
System.out.println("Connected database successfully...");
// Execute create query
System.out.println("Creating table in given database...");
stmt = conn.connect().createStatement();
String sql = "CREATE TABLE A_BILL__tab " + "(pid INTEGER not NULL AUTO_INCREMENT, " + " id VARCHAR(10), " + " income numeric(8,2), " + " pep VARCHAR(4), " + " PRIMARY KEY ( pid ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
conn.connect().close(); //close db connection
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}
}
public void insertRecords(BankRecords[] torbs) {
try {
// Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.connect().createStatement();
String sql = null;
// Include all object data to the database table
for (int i = 0; i < torbs.length; ++i) {
// finish string assignment to insert all object data
// (id, income, pep) into your database table
String ID = torbs[i].getID();
double income=torbs[i].getIncome();
String pep=torbs[i].getPep();
sql = "INSERT INTO A_BILL__tab(ID,INCOME, PEP) " + "VALUES (' "+ID+" ', ' "+income+" ', ' "+pep+" ' )";
stmt.executeUpdate(sql);
}
conn.connect().close();
} catch (SQLException se) { se.printStackTrace(); }
}
public ResultSet retrieveRecords() {
ResultSet rs = null;
try {
stmt = conn.connect().createStatement();
System.out.println("Retrieving records from table...");
String sql = "SELECT ID,income,pep from A_BILL__tab order by pep desc";
rs = stmt.executeQuery(sql);
conn.connect().close();
} catch (SQLException se) { se.printStackTrace();
}
return rs;
}
}
Expected results would be printlns for the table functions (inserting records and so on), the headings, the data values for the first 10 files, and the date and time of when the program was run. Actual results were some of the table functions, headings and then the time when the program ran not including when it errors me out with table already created. I'm not exactly sure where or how to fix these issues.
you're getting this exception because every time you run your code, your main method calls dao.createTable();, and if the table is already created, it will throw an exception. So for this part, use a verification to check if the table is already created.
I'm not really sure where you created the variable torbs, but also make sure its properties are not null before inserting them to the database.

Java Embedded Database h2

i am trying to make a simple application using h2 Database. Program is working perfectly just for one time. when i am tying to insert more data, following error occurred.
org.h2.jdbc.JdbcSQLException: Database may be already in use: "C:/Users/ali/bookDB.mv.db". Possible solutions: close all other connection(s); use the server mode [90020-186]
java.lang.IllegalStateException: The file is locked: nio:C:/Users/ali/bookDB.mv.db [1.4.186/7]
Code is
package h2_basic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class H2_Basic {
public static void main(String[] args) {
try{
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:~/bookDB","test","test");
Statement sta = con.createStatement();
String CREATE_TABLE = "CREATE TABLE BOOKS "
+ "(bookid bigint auto_increment NOT NULL PRIMARY KEY, "
+ " booktitle VARCHAR(255), "
+ " bookauthor VARCHAR(255), "
+ " editiondate VARCHAR(255))";
sta.execute(CREATE_TABLE);
String sql = "INSERT INTO BOOKS (booktitle, bookauthor, editiondate) VALUES ('ali','ali','12')";
sta.execute(sql);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Change your JDBC URL to jdbc:h2:~/bookDB;AUTO_SERVER=TRUE, as in
DriverManager.getConnection("jdbc:h2:~/bookDB;AUTO_SERVER=TRUE","test","test");
to start H2 in Automatic Mixed Mode.

need help setting up SQLite on eclipse with java for the first time

I have been trying to figure out how to get SQLite working on eclipse juno. I have been following the instructions on this site http://wiki.eclipse.org/Connecting_to_SQLite. The problem is not every step is exactly as explained so I am guessing on weather I got it right or not. I feel that I have probably gotten it all correct until step 13, there is no SQL Model-JDBC Connection entry. So I have tried step 13-16 with a generic JDBC and with one that says SQLite. The SQLite one does not have a driver which is no surprise due to step 5. Any way that I have tried so far ends up failing ping with details listed below. Someone must have a better way through this process.
java.sql.SQLException: java.lang.UnsatisfiedLinkError: SQLite.Database.open(Ljava/lang/String;I)V
at SQLite.JDBCDriver.connect(JDBCDriver.java:68)
at org.eclipse.datatools.connectivity.drivers.jdbc.JDBCConnection.createConnection(JDBCConnection.java:328)
at org.eclipse.datatools.connectivity.DriverConnectionBase.internalCreateConnection(DriverConnectionBase.java:105)
at org.eclipse.datatools.connectivity.DriverConnectionBase.open(DriverConnectionBase.java:54)
at org.eclipse.datatools.connectivity.drivers.jdbc.JDBCConnection.open(JDBCConnection.java:96)
at org.eclipse.datatools.connectivity.drivers.jdbc.JDBCConnectionFactory.createConnection(JDBCConnectionFactory.java:53)
at org.eclipse.datatools.connectivity.internal.ConnectionFactoryProvider.createConnection(ConnectionFactoryProvider.java:83)
at org.eclipse.datatools.connectivity.internal.ConnectionProfile.createConnection(ConnectionProfile.java:359)
at org.eclipse.datatools.connectivity.ui.PingJob.createTestConnection(PingJob.java:76)
at org.eclipse.datatools.connectivity.ui.PingJob.run(PingJob.java:59)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)
Make sure you get the driver from https://bitbucket.org/xerial/sqlite-jdbc/downloads, then import the driver into your project.
Now you can test the configuration by creating a java class Sample.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("DROP TABLE IF EXISTS person");
statement.executeUpdate("CREATE TABLE person (id INTEGER, name STRING)");
int ids [] = {1,2,3,4,5};
String names [] = {"Peter","Pallar","William","Paul","James Bond"};
for(int i=0;i<ids.length;i++){
statement.executeUpdate("INSERT INTO person values(' "+ids[i]+"', '"+names[i]+"')");
}
//statement.executeUpdate("UPDATE person SET name='Peter' WHERE id='1'");
//statement.executeUpdate("DELETE FROM person WHERE id='1'");
ResultSet resultSet = statement.executeQuery("SELECT * from person");
while(resultSet.next())
{
// iterate & read the result set
System.out.println("name = " + resultSet.getString("name"));
System.out.println("id = " + resultSet.getInt("id"));
}
}
catch(SQLException e){ System.err.println(e.getMessage()); }
finally {
try {
if(connection != null)
connection.close();
}
catch(SQLException e) { // Use SQLException class instead.
System.err.println(e);
}
}
}
}
The code will create a database named sample.db, inserting data into, and then prints the rows.

How to check if a table or a column exists in a database?

I am trying to make simple java code that will check if a table and/or a column exists in a MySQL DB. Should I use Java code to do the checking or make a SQL query string and execute that to do the checking ?
EDIT-
# aleroot -
I tried using your code as shown below. I don't see any tables or columns when I run the code below. I only see this-
Driver Loaded.
Got Connection.
My DB has got a lot of DB's, tables and columns. I dont know why this program works properly.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Tester {
static Connection conn;
static Statement st;
public static void main(String[] args) throws Exception {
try {
// Step 1: Load the JDBC driver.
System.out.println("Driver Loaded.");
// Step 2: Establish the connection to the database.
String url = "jdbc:mysql://localhost:3306/";
conn = DriverManager.getConnection(url, "cowboy", "123456");
System.out.println("Got Connection.");
st = conn.createStatement();
} catch (Exception e) {
System.err.println("Got an exception! ");
e.printStackTrace();
System.exit(0);
}
DatabaseMetaData md2 = conn.getMetaData();
ResultSet rsTables = md2.getColumns(null, null, "customers", "name");
if (rsTables.next()) {
System.out.println("Exists !");
}
}
}
To check if a table exist you can use DatabaseMetaData in this way :
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "table_name", null);
if (rs.next()) {
//Table Exist
}
And to check if a column exist you can use it in a similar way :
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getColumns(null, null, "table_name", "column_name");
if (rs.next()) {
//Column in table exist
}
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='table_schema'
AND TABLE_NAME='table_name'
AND COLUMN_NAME='column_name'
If this sql returns nothing - column not exists. You can execute this query on java side, but this depends what you use (JPA, JDBC, JDBCTemplate).
In Apache Derby (SQL)
E.g. check if column exists:
SELECT ss.SCHEMANAME, st.TABLENAME, sc.COLUMNNAME FROM SYS.SYSSCHEMAS ss
INNER JOIN SYS.SYSTABLES st ON st.SCHEMAID = ss.SCHEMAID AND st.TABLENAME = <YOUR TABLE NAME>
INNER JOIN SYS.SYSCOLUMNS sc ON sc.REFERENCEID = st.TABLEID AND sc.COLUMNNAME = <YOUR COLUMN NAME>
WHERE ss.SCHEMANAME = <YOUR SCHEMA>
Knowing that you can practically select a column from a table using the following SQL statement (in MySQL):
show columns from TABLE_NAME where field = 'FIELD_NAME';
You could do something like:
...
PreparedStatement preparedStatement =
connection.prepareStatement(
"show columns from [TABLE_NAME] where field = ?");
preparedStatement.setString(1, columName);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("column exists!");
} else {
System.out.println("column doesn't exists!");
}
...

Categories

Resources