Syntax error on token "<=", invalid AssignmentOperator - java

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.

Related

Having Trouble filling a LocalDateTime array with data from MySQL database

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;
}

Make this program more efficient?

just curious if anyone has any idea for making this program more simple. It reads records from a database into an ArrayList and allows the user to search for records by state. It processes a database of 1 million records in aprox 16000ms.
import java.sql.*;
import java.util.*;
public class ShowEmployeeDB
{
public static void main(String args[])
{
ArrayList <String> Recs = new ArrayList <String>();
String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
String connectionURL = "jdbc:odbc:CitizensDB";
Connection con = null;
Statement stmt = null;
String sqlStatement = "SELECT * FROM Citizens";
ResultSet rs = null;
int r = 0;
Scanner scan = new Scanner(System.in);
String search = null;
long starttime = System.currentTimeMillis();
try
{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(connectionURL);
stmt = con.createStatement();
rs = stmt.executeQuery(sqlStatement);
String ID = null;
String Age = null;
String State = null;
String Gender = null;
String Status = null;
String record = null;
while (rs.next())
{
for (int k = 1; k <= 1; ++k)
{
ID = rs.getString(k) + " ";
for (int j = 2; j <= 2; ++j)
Age = rs.getString(j) + " ";
for (int i = 3; i <= 3; ++i)
State = rs.getString(i).toUpperCase() + " ";
for (int h = 4; h <= 4; ++h)
Gender = rs.getString(h) + " ";
for (int g = 5; g <= 5; ++g)
Status = rs.getString(g) + " ";
}//for
record = ID + Age + State + Gender + Status;
Recs.add(record);
++r;
}//while
rs.close();
stmt.close();
con.close();
} catch (Exception ex) { ex.printStackTrace(); }
String endtime = System.currentTimeMillis() - starttime + "ms";
System.out.println(endtime);
System.out.print("Enter A Search State: ");
search = scan.nextLine().toUpperCase();
Iterator<String> iter = Recs.iterator();
while(iter.hasNext())
{
String s = iter.next();
if (s.contains(search))
{
System.out.println(s);
}
}//while
} // main
} // ShowEmployeeBD
Any advice would be greatly appreciated. Thank you in advance!
If search is not often, I would suggest to take the search string input before running the query, so that search results are directly from the DB. I this case you do not have to reiterate all 1 million records.
Perform searching directly on DB rather than fetching all the records and searching through java code.
Also if search is on multiple column, then prepare a meta data in DB at a single place on the basis of IDs, and the meta data can further be used for fetching the required results that match the query.
Separate your logic from the technical stuff. In such a convolut it is difficult to run unit tests or any optimizations.
Why do you need for loops, when only asking one value.
Use StringBuilder instead of String concatenation.
Use either try-with or put your close statements in a finally clause.
Don't initialize variables you don't need (r).
Use for each statements.
Query the database, not the result set.
Tune your database.
If you are only searching for a state, filter only those, so build an object and compare the state instead of a string contains.
Compare the state before storing strings in the list.
Tune your list because it constantly grows with 1Mio records.
Use a hashset instead of an arraylist.
Develop against interfaces.
A better program might look like following:
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ShowEmployeeDB {
private static final String DRIVERNAME = "sun.jdbc.odbc.JdbcOdbcDriver";
private static final String CONNECTIONURL = "jdbc:odbc:CitizensDB";
private static final String SELECT_CITIZENS = "SELECT * FROM Citizens";
static {
try {
DriverManager.registerDriver((Driver) Class.forName(DRIVERNAME).newInstance());
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static void main(final String args[]) {
System.out.print("Enter A Search State: ");
searchRecords();
}
private static void searchRecords() {
try(Scanner scan = new Scanner(System.in);) {
final String state = scan.nextLine();
final long starttime = System.currentTimeMillis();
final Set<Record> records = searchRecordsByState(state);
System.out.println(System.currentTimeMillis() - starttime + "ms");
for(final Record r : records) {
System.out.println(r);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Set<Record> searchRecordsByState(final String stateToFilter) {
final Set<Record> records = new HashSet<>();
try(Connection con = DriverManager.getConnection(CONNECTIONURL);
PreparedStatement stmt = con.prepareStatement(SELECT_CITIZENS);
ResultSet rs = stmt.executeQuery(); ) {
while(rs.next()) {
final String state = rs.getString(3);
if(state.equalsIgnoreCase(stateToFilter)) {
final Record r = new Record(rs.getString(1), rs.getString(2), state, rs.getString(4), rs.getString(5));
records.add(r);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return records;
}
}
class Record {
String id, age, state, gender, status;
public Record(String id, String age, String state, String gender, String status) {
this.id = id;
this.age = age;
this.state = state;
this.gender = gender;
this.status = status;
}
public String getState() {
return state;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(id).append(' ')
.append(age).append(' ')
.append(state).append(' ')
.append(gender).append(' ')
.append(status);
return sb.toString();
}
}
This is untested, because I don't have a database with a million entries by hand.
But the best would be to query the database and catch only those entries you need. So use the WHERE-clause in your statement.

How to generate random code and check whether it exist in database or not

I try to generate random code name as licenseKey and check whether it is exist in database or not. If not exist, then display in my jsp page, if exist, continue generating the random code. I got the error "java.lang.StackOverflowError". How to solve this? Below is my code :
package com.raydar.hospital;
import com.raydar.hospital.DB_Connection;
import java.sql.*;
public class RandomCodeGenerator {
String licenseKey = "";
int noOfCAPSAlpha = 4;
int noOfDigits = 4;
int minLen = 8;
int maxLen = 8;
char[] code = RandomCode.generateCode(minLen, maxLen, noOfCAPSAlpha, noOfDigits);
public RandomCodeGenerator(){
}
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
System.out.println("4 + " +result);
if (result=="false"){
System.out.println("1 + " +new String(code));
licenseKey = new String(code);
}
else if (result=="true"){
System.out.println("2 + " +new String(code));
licenseKey = new String(code);
isLicenseKeyExist ();
}
return licenseKey;
}
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
String result="";
System.out.println("3 + " +code);
try{
DB_Connection connect = new DB_Connection();
connection = connect.getDBConnection();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT licenseKey FROM hospital WHERE licenseKey = '" +code+ "'");
if (rs.next()){
result = "true";
}
else{
result = "false";
}
}catch (Exception e){
System.out.println("Error retrieving data! "+e);
}
return result;
}
}
You create a recursive loop where isLicenseKeyExist() calls getOutputCode(), but then getOutputCode() calls isLicenseKeyExist(). So eventually you run out of stack space, and get this exception.
Here,
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
...
}
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
...
}
I think you want something like this. Remove the field called code from your class, and its initialiser, and put the call to RandomCode.generateCode inside your getOutputCode method like this. The reason is that you'll have to call it repeatedly if your code is already in the database.
public String getOutputCode() throws SQLException {
String code;
do {
code = new String(RandomCode.generateCode(minLen, maxLen, noOfCAPSAlpha, noOfDigits));
}
while(licenceKeyExists(code));
return code;
}
private boolean licenceKeyExists(String code) throws SQLException {
try{
DB_Connection connect = new DB_Connection();
connection = connect.getDBConnection();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT licenseKey FROM hospital WHERE licenseKey = '" +code+ "'");
return rs.next();
}
finally {
try {
connection.close();
} catch (SQLException ignored){}
}
}
#aween - #captureSteve has answered the first part of the question .
So, straight to "I wan't to call this function" comment. See, if I
understand your question correctly, you want to generate a key, and
check if it is available in the DB using isLicenseKeyExist() . In such
case, why don't you create the key first, then pass it to the
isLicenseKeyExist(). Then this function will return true/false based
on which you can decide what to do.

connect client side java program to access database

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.

connector for Pervasive [duplicate]

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

Categories

Resources