How can I create a connector for Pervasive PSQL in Java?
How can I create a connector for Pervasive PSQL? I created a sample connector, but I am not sure whether it is right or wrong.
Here's a simple program I have that works for me to connect to a Pervasive PSQL database:
/*
* SQLStatement.java
* Simple JDBC Sample using Pervasive JDBC driver.
*/
import java.*;
import java.sql.*;
import pervasive.jdbc.*;
import java.io.*;
public class SQLStatement {
public static void main(String args[]) {
String url = "jdbc:pervasive://localhost:1583/demodata?transport=tcp";
Connection con;
String query = "select* from class";
Statement stmt;
try {
Class.forName("com.pervasive.jdbc.v2.Driver");
} catch(Exception e) {
System.err.print("ClassNotFoundException: ");
System.out.println(e.toString());
System.err.println(e.getMessage());
}
try {
Connection conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int rowCount = 1;
long j = 0;
int i = 1;
while (rs.next()) {
System.out.println("Row " + rowCount + ": ");
for (i = 1; i <= numberOfColumns; i++) {
System.out.print(" Column " + i + ": ");
System.out.println(rs.getString(i));
}
System.out.println("");
rowCount++;
}
System.out.println("Waiting.");
String thisLine;
try {
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(converter);
while ((thisLine = br.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error: " + e);
}
stmt.close();
conn.close();
} catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
}
}
To compile it, I use:
javac -classpath "C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2.jar";"C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2x.jar";"C:\Program Files\Pervasive Software\PSQL\bin\jpscs.jar";. SQLStatement.java
And to run it, I use:
java -classpath "C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2.jar";"C:\Program Files\Pervasive Software\PSQL\bin\pvjdbc2x.jar";"C:\Program Files\Pervasive Software\PSQL\bin\jpscs.jar";.\ SQLStatement.java
You might need to change the location of the PSQL JAR files if you are using a 64-bit OS.
I use the following library with Dbeaver for querying in a Pervasive database:
jpscs.jar
pvjdbc2x.jar
pvjdbc2.jar
Related
I'm using a MySQL database to hold information for my reminder application in Java. I'm trying to pull the information out and store it in an array and the compare each element of the array to an updating current timestamp. The issue is the code I have gives a nullpointer exception and I can't figure out why. It works when the LocalDateTime isn't an array but the moment I turn it into an array it throws the error. It also demands I initialize it to null over anything else.
Thoughts on how I can fix this? Any help is appreciated.
Here's the method in question.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
Heres the exception thrown
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#6dfc1e5f
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#3b2da18f
Found a solution.
I needed to initialize a size for the array in order to fill it. So I created another method that went through all the elements and gets the size.
Here's the code.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
reminderTime = new LocalDateTime[getSizeOfRs()];
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
and the get rs size
public static int getSizeOfRs()
{
String SQL = "SELECT * FROM reminder_database.reminder;";
int size = 0;
try {
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
for(int i = 0; rs.next(); i++)
size++;
}
catch(Exception e)
{
System.out.println("Exception thrown with getSizeofRS --> " + e + e.getStackTrace());
}
return size;
}
I have three fields of a table orderinfo ,having around 2500 rows in my database.
Now I want to store each and every field data in a array variable.
when i run the code, I am getting Null values stored on the array variable.
Below I have provided my code.
Can any one help me to achieve this?
Thanks in advance.
package com;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import com.mysql.jdbc.exceptions.MySQLSyntaxErrorException;
public class getOrderinfo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.10.10.14/opsbank-ii";
static final String USER = "root";
static final String PASS = "p#ssw0rd";
public static int row_count = 0;
public static int count_for_totalfiles = 0;
public static String filename_allocated = "";
public static String dateofcar_allocated = "";
public String row_data = "";
public static int orderid = 0;
public static int[] orderid_sto = new int[5000];
public static String flow = "";
public static String[] flow_sto = new String[5000];
public static Date dateofprocessing;
public static Date[] dateofprocessing_sto = new Date[5000];
public static void main(String args[]) {
//public static void main(String[] args)
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Date(Format : 2016-02-22) ");
String date = scanner.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date2 = null;
/* try {
//Parsing the String
date2 = (Date) dateFormat.parse(date);
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println("Input Date:" + date2);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "select orderid,flow,dateofprocessing from orderinfo where ordertype ='CAR' and dateofprocessing like '%" + date + "%'";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while (rs.next()) {
int i = 0;
orderid = rs.getInt("orderid");
System.out.println("Order ID get : " + orderid);
orderid_sto[i++] = orderid;
flow = rs.getString("flow");
flow_sto[i++] = flow;
dateofprocessing = rs.getDate("dateofprocessing");
dateofprocessing_sto[i++] = dateofprocessing;
System.out.println("orderid :" + orderid + " || Flow : " + flow + " || date : " + dateofprocessing);
i++;
row_count++;
count_for_totalfiles++;
//Display values
//System.out.print("BOOKISSID: " + BOOKISSID);
//System.out.print(", ISSN: " + ISSN);
//System.out.println("\n");
}
System.out.println("Total Number of CAR orders found for the date : " + date2 + " = " + row_count);
System.out.println("The Details after calculation:\n");
for (int j = 0; j < count_for_totalfiles; j++) {
System.out.println("I am executed number : " + j);
System.out.println("orderid :" + orderid_sto[j] + " || Flow : " + flow_sto[j] + " || date: " + dateofprocessing_sto[j]);
}
// row_count=0;
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (MySQLSyntaxErrorException mysqlerr) {
System.out.println("date issue");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
}//end main
}//end FirstExample
Kindly help any one if possible.
Try to increment i once time like this:
orderid_sto[i]=rs.getInt("orderid");
flow_sto[i]=rs.getString("flow");
dateofprocessing_sto[i]=rs.getDate("dateofprocessing");
i++;
And remove these line because they are present in finally block:
//STEP 6: Clean-up environment
stmt.close();
conn.close();
You should only increment i once, you are incrmenting it multiple times
your code:
orderid_sto[i++]=orderid;
flow=rs.getString("flow");
flow_sto[i++]=flow;
dateofprocessing=rs.getDate("dateofprocessing");
dateofprocessing_sto[i++]=dateofprocessing;
i++;
I need my java program to connect to an Excel spreadsheet.
I have completed the System DSN and have used the code below. However, on run time, an error throws in regards to 'sun.jdbc.obdc.jdbcodbcDriver' on line 4. I have done a lot of research around Stackoverflow and other sites but finding no direct solution.
Any advice would be appreciated.
import java.sql.*;
public class DBConnection {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:[B]Testsheet[/B]");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from [Sheet1$]");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue);
}
System.out.println("");
}
st.close();
con.close();
} catch (Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
}
}
Error message:
Error: sun.jdbc.odbc.JdbcOdbcDriver
I'm attempting to fix a plugin I wrote a long time ago for Craftbukkit, but I'm stumped on one section. I've searched Google with little luck, and I've asked other Java developers only to hear that I shouldn't be using a for loop because it's rather basic, or that I'm using a boolean expression in the wrong place. Nobody will tell me how I can fix this, so I'll know for future references - Below is the class that throws the error:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.logging.Logger;
import org.bukkit.configuration.file.FileConfiguration;
public class Database
{
private static String host = null;
private static String port = null;
private static String database = null;
private static String table = null;
private static String username = null;
private static String password = null;
private static String colUsername = null;
private static Logger logger = null;
public static void init(FileConfiguration config, Logger log)
{
logger = log;
host = config.getString("DBHost");
port = config.getString("DBPort");
database = config.getString("DBName");
table = config.getString("DBTable");
username = config.getString("DBUser");
password = config.getString("DBPass");
colUsername = config.getString("ColUsername");
}
public static Hashtable<String, Object> getUserInfo(String user)
{
String url = "jdbc:mysql://" + host + ":" + port + "/" + database;
String query = "SELECT * FROM " + table + " WHERE " + colUsername + " = ?";
Connection connect = null;
PreparedStatement stmt = null;
ResultSet result = null;
Hashtable<String, Object> userInfo = new Hashtable<String, Object>();
try
{
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection(url, username, password);
stmt = connect.prepareStatement(query);
stmt.setString(1, user);
result = stmt.executeQuery();
ResultSetMetaData rsmd;
int i;
for (; result.next(); i <= rsmd.getColumnCount())
{
rsmd = result.getMetaData();
i = 1; continue;
userInfo.put(rsmd.getColumnName(i), result.getObject(i));i++;
}
return userInfo;
}
catch (ClassNotFoundException e)
{
logger.warning("Unable to load driver. Using default behaviour.");
e.printStackTrace();
}
catch (SQLException e)
{
logger.warning("Database error. Using default behaviour.");
e.printStackTrace();
}
finally
{
if (result != null) {
try
{
result.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (stmt != null) {
try
{
stmt.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (connect != null) {
try
{
connect.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
return null;
}
}
The error I encounter is in this part of the code:
for (; result.next(); i <= rsmd.getColumnCount())
{
rsmd = result.getMetaData();
i = 1; continue;
userInfo.put(rsmd.getColumnName(i), result.getObject(i));i++;
}
Where I get the error "Syntax error on token "<=", invalid AssignmentOperator"
How should I go about fixing this, and how can I improve it?
EDIT #1:
This is my updated code, according to Jon's answer:
try
{
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection(url, username, password);
stmt = connect.prepareStatement(query);
stmt.setString(1, user);
result = stmt.executeQuery();
ResultSetMetaData rsmd = result.getMetaData();
while (result.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
rsmd = result.getMetaData();
userInfo.put(rsmd.getColumnName(i), result.getObject(i));i++;
}
}
return userInfo;
}
Basically this is the wrong way round:
for (; result.next(); i <= rsmd.getColumnCount())
It should possibly be:
for (; i <= rsmd.getColumnCount(); result.next())
Although more likely, you actually want:
while (result.next()) {
// This outer loop is executed once per row
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
// This inner loop is executed once per column (per row, as it's
// within the outer loop)
}
}
Having said that, you're not even initializing rsmd, which doesn't help. I suspect you may want to call ResultSet.getMetadata(), e.g.
rsmd = result.getMetadata();
For reference, the three parts of the for statement declaration are as follows:
The first part (empty in your case) is performed once, as initialization
The second part is a condition to check on each iteration; the loop ends when the condition evaluates to false
The third part is a statement is a step to take at the end of each iteration
See section 14.14.1 of the JLS or the for statement part of the Java tutorial for more details.
This won't work in the last part of a for loop:
i <= rsmd.getColumnCount()
Perhaps you meant this?
for (; i <= rsmd.getColumnCount(); result.next())
Basic syntax of a for-loop:
for (any; boolean; any)
your's is
for (any; any; boolean)
Just change the order.
I am making a practice program using java and an access database.
the program is an ultimate tictactoe board and the databse is meant for keeping track of the names of the players and their scores.
the trouble i am having is that i keep getting these errors.
Exception in thread "main" java.lang.NullPointerException
at AccessDatabaseConnection.getName(AccessDatabaseConnection.java:39)
at ultimate.<init>(ultimate.java:39)
at ultimate.main(ultimate.java:82)
with further research i also found this:
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
here is my code. the math is a little unfinished in the sql statements but im not really worried about that yet. i need to get this connection between the program and the database.
here is the area of code in my constructor for the program that connects to the accessdatabaseconnections class:
AccessDatabaseConnection DB = new AccessDatabaseConnection();
Font f = new Font("Dialog", Font.BOLD, 80);
public ultimate() {
super("Testing Buttons");
String dbname = DB.getName();
String wins = DB.getWins();
String losses = DB.getLosses();
Container container = getContentPane();
container.setLayout(null);
ButtonHandler handler = new ButtonHandler();
for (int j = 0; j < 9; j++) {// set the rows
x = 10;
for (int i = 0; i < 9; i++) {// set the columns
button[j][i] = new JButton();
container.add(button[j][i]);
button[j][i].setName(Integer.toString(j) + "_"
+ Integer.toString(i));
button[j][i].addActionListener(handler);
button[j][i].setSize(100, 100);
button[j][i].setVisible(true);
button[j][i].setFont(f);
button[j][i].setText(null);
if ((i > 2 && j < 3 && i < 6) || (j > 2 && j < 6 && i < 3)
|| (j > 2 && j < 6 && i < 9 && i > 5)
|| (j > 5 && j < 9 && i < 6 && i > 2)) {
button[j][i].setBackground(Color.LIGHT_GRAY);
} else {
button[j][i].setBackground(Color.WHITE);
}
button[j][i].setLocation(x, y);
x = x + 110;
}
y = y + 110;
}
setSize(1024, 1050);
setVisible(true);
container.setBackground(Color.BLACK);
}
public static void main(String args[]) {
ultimate application = new ultimate();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PlayerOne = JOptionPane.showInputDialog("Player 1: Enter Your Name");
PlayerTwo = JOptionPane.showInputDialog("Player 2: Enter Your Name");
while(PlayerOne == PlayerTwo){
PlayerTwo = JOptionPane.showInputDialog("Player 2: Re-Enter Your Name (Cannot be the same!)");
}
}
and here is the code for accessing the database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AccessDatabaseConnection {
public static Connection connect() {
Connection con;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database ="jdbc:odbc:Driver{Microsoft Access Driver (*.accdb)};DBQ=C:\\Users\\McKenzieC\\Documents\\tictactoeRecords.accdb;";
con = DriverManager.getConnection(database, "", "");
} catch (Exception ex) {
return null;
}
return con;
}
public void addData(String nameOne, int win, String nameTwo,int loss){
try {
Statement stmt = connect().createStatement();
stmt.executeQuery("INSERT INTO t_Records (Name, Wins) " +
"VALUES (" + nameOne + ", " + Integer.toString(win));
/*stmt.executeQuery("INSERT INTO t_Records (Name, Wins) " +
"VALUES (" + nameTwo + ", " + Integer.toString(loss));
+ ", " + Integer.toString(loss)*/
}
catch (SQLException ex) {
}
}
public String getName() {
try {
Statement stmt = connect().createStatement();
ResultSet rset = stmt.executeQuery("SELECT * FROM t_Records");
if (rset.next()) {
String name = rset.getString("Name");
return name;
}
} catch (SQLException ex) {
}
return null;
}
public String getWins() {
try {
Statement stmt = connect().createStatement();
ResultSet rset = stmt.executeQuery("SELECT * FROM t_Records");
if (rset.next()) {
String wins = rset.getString("Wins");
return wins;
}
} catch (SQLException ex) {
}
return null;
}
public String getLosses() {
try {
Statement stmt = connect().createStatement();
ResultSet rset = stmt.executeQuery("SELECT * FROM t_Records");
if (rset.next()) {
String losses = rset.getString("Losses");
return losses;
}
} catch (SQLException ex) {
}
return null;
}
public static void main(String[] args) {
}
}
I assume that you can't see the real error because you're hiding the real error:
Never do this:
catch (Exception ex) {
return null;
}
You can change for this at least (again not recommended but better than the above code):
catch (Exception ex) {
ex.printStackTrace();
return null;
}
//After this change the program will fail again but you will got a better error message
But you always must manage the Exception:
Print a error message
Put a log message (java logging, log4j and so on)
Deal with the error
Re-throw the exception
And son on
The statement...
String database ="jdbc:odbc:Driver{Microsoft Access Driver (*.accdb)};DBQ=C:\\Users\\McKenzieC\\Documents\\tictactoeRecords.accdb;";
...has two problems:
You are missing the equal sign (=) after the Driver keyword.
There is no ODBC driver named Microsoft Access Driver (*.accdb).
Try this instead:
String database ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\McKenzieC\\Documents\\tictactoeRecords.accdb;";
Is Statement stmt equal null after connect().createStatement();? If yes, then stmt.executeQuery will cause null ptr exception.