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.
Related
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 3 years ago.
My select statement shows the error
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'condition from food' at line 1.
My parameter values are object = "food" and columns[] = {"foodName, foodPrice, condition"}
This function still works for my login though
I already use different versions of mySQL and also put brackets around the statement and it still doesn't work
public static String[][] checkDatabase(String object, String[] columns){
Connection myCon = null;
Statement myStm = null;
ResultSet myRs = null;
try {
myCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/softwaredesignorder", "root","SeanLink_11");
myStm = myCon.createStatement();
String temp = "select ";
for (int i = 0; i < columns.length; i++) {
if (i < columns.length - 1) {
temp = temp + columns[i] + ", ";
} else {
temp = temp + columns[i];
}
}
temp = temp + " from " + object;
//PreparedStatement pStm = myCon.prepareStatement(temp);
//pStm.execute();
myRs = myStm.executeQuery(temp);
myRs.last();
String[][] returner = new String[myRs.getRow()][columns.length];
myRs.beforeFirst();
int row = 0;
while (myRs.next()){
int length = columns.length, col = 0;
while (length != 0) {
try {
returner[row][col] = myRs.getString(columns[col]);
} catch (IllegalArgumentException e1) {
try {
returner[row][col] = Integer.toString(myRs.getInt(columns[col]));
} catch (IllegalArgumentException e2) {
try {
returner[row][col] = Double.toString(myRs.getDouble(columns[col]));
} catch (IllegalArgumentException e3) {
try {
Date date = myRs.getDate(columns[col]);
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
returner[row][col] = dateFormat.format(date);
} catch (IllegalArgumentException e4) {
System.err.println("Could not retrieve data");
} catch (Exception e) {
System.err.println(e);
}
}
}
}
col += 1;
length -= 1;
}
row += 1;
}
return returner;
} catch (SQLException exSQL) {
System.err.println(exSQL);
}
return null;
};
I want the output to have the data from the entire table but only the selected column.
I believe your problem is that condition is a reserved work in most SQL languages as detailed in https://dev.mysql.com/doc/refman/5.5/en/keywords.html#keywords-5-5-detailed-C, that is why your code works on some cases, is because you don't always have a column named condition you need to escape it using backticks.
Have you try to output back the query you made? i think this one have issue on your query builder. Just simply System.out.println(temp) and check the query syntax before you query on MySQL.
"conditional" is a reserved word in MySQL. You could avoid this error by surrounding your select list items with quotes:
for (int i = 0; i < columns.length; i++) {
String column = "\"" + colunms[i] + "\"";
if (i < columns.length - 1) {
temp = temp + column + ", ";
} else {
temp = temp + column;
}
}
I'm trying to work through creating a very simple class to send queries to an instance of Oracle XE 11g, essentially making a very simple SQL*Plus to get the basics of JDBC down.
The source code I'm currently working with is:
public class Example {
static String username, password;
static String dbDriver = "oracle.jdbc.driver.OracleDriver";
static String dbConnection = "jdbc:oracle:thin:#//localhost:1521/xe";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String line;
Connection c = null;
Statement stmt = null;
int loginAttempts = 0;
// Log in loop
do {
try {
Class.forName(dbDriver);
System.out.print("Enter username: ");
line = input.nextLine();
if (line.contains("/")) {
String[] login = line.split("/");
if (login.length != 2) {
System.out
.println("Unrecognized information, exiting...");
System.exit(0);
}
username = login[0].trim();
password = login[1].trim();
} else {
username = line;
System.out.print("Enter password: ");
password = input.nextLine();
}
c = DriverManager.getConnection(dbConnection, username,
password);
stmt = c.createStatement();
loginAttempts = -1;
} catch (ClassNotFoundException e) {
System.err.println("Unable to connect to database, exiting...");
System.exit(-1);
} catch (SQLException e) {
System.out.println("Username and/or password is incorrect");
if (++loginAttempts == 1) {
System.out.println("Too many failed login attempts, exiting...");
System.exit(0);
}
}
} while (loginAttempts != -1);
// Input loop
for (;;) {
try {
// Write out the prompt text and wait for input
if(c == null) {
throw new IllegalStateException("Connection should not be null");
}
System.out.print(c.getSchema() + ":> ");
String tmp = input.nextLine();
// Check if the user entered "exit"
if (tmp.toLowerCase().equals("exit")) {
System.out.println("Exiting...");
input.close();
System.exit(0);
}
String query;
// TODO: For some reason, no semi-colon is allowed
if (tmp.charAt(tmp.length() - 1) == ';')
query = tmp.split(";")[0];
else
query = tmp;
// System.out.println(query);
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData rmd = rset.getMetaData();
int colCount = rmd.getColumnCount();
// Column indices start with 1, print column names
for (int i = 1; i <= colCount; i++) {
System.out.printf("%-20.20s ", rmd.getColumnName(i));
}
System.out.println();
while (rset.next()) {
for (int i = 0; i < colCount; i++) {
System.out.printf("%-20.20s | ", rset.getString(i + 1));
}
System.out.println();
}
System.out.println();
} catch (SQLSyntaxErrorException e) {
System.out.println("Encountered a syntax error:\n"
+ e.getMessage());
} catch (SQLException e) {
System.err.println("An unexpected error occurred");
e.printStackTrace();
input.close();
System.exit(-1);
}
}
}
}
In the second try/catch block, in the for(;;) loop, I get the following output:
Enter username: hr/hr
Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.T4CConnection.getSchema()Ljava/lang/String;
at jdbctest.Example.main(Example.java:69)
I checked out the Oracle docs (java.lang.AbstractMethodError), and it says that this error can only be thrown if:
"the definition of some class has incompatibly changed since the currently executing method was last compiled."
I'm thinking that there's something I'm missing with line 27, but I'm not sure how to approach this problem and any guidance would be extremely helpful.
I believe that your problem is due to the fact that you use a JDBC driver for a version of Java <= 6 and you use Java 7 or higher because the method Connection#getSchema() has been added in Java 7.
Use the latest version of your JDBC driver to avoid such issue or at least a JDBC driver compatible with your version of Java.
This works on DB2 (and an old version of the driver)
Connection.getMetaData().getConnection().getSchema();
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++;
This is the code:
import java.util.*;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.io.Console;
class SynchList {
ArrayList<PrintStream> it;
SynchList() {
it = new ArrayList<PrintStream>();
}
synchronized PrintStream get(int i) {
return it.get(i);
}
synchronized void add(PrintStream o) {
it.add(o);
}
synchronized int size() {
return it.size();
}
synchronized void remove(PrintStream o) {
it.remove(o);
}
}
class StringBroadcaster {
static SynchList Outputs = new SynchList();
static int i = 0;
public static void main(String[] args) throws Exception {
String message;
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Database password
Console cons;
char[] passwd;
String pass = "";
if ((cons = System.console()) != null &&
(passwd = cons.readPassword("%s", "Password:")) != null) {
for (int i = 0; i < passwd.length; i++) pass += passwd[i];
}
//Open a connection
Connection connect = DriverManager.getConnection("jdbc:mysql://igor.gold.ac.uk/ma203mk", "ma203mk", pass);
//Execute a query to create a statement with required arguments
Statement st = connect.createStatement();
int resultSet = st.executeUpdate(SQLquery);
//Execute a query
SQLquery = "INSERT INTO one (Port,Name,Message) VALUES('a','hello','hii')";
VALUES(1, 'hello', 'muhsina') ");
int port = Integer.parseInt(args[0]);
ServerSocket s = new ServerSocket(port);
Transaction k;
while (true) {
k = new Transaction(Outputs.size(), s.accept(), Outputs);
k.start();
System.out.println("Client Joined");
}//wait for client to connect
}
}//End of Main
class Transaction extends Thread {
SynchList outputs;
public int n;
Socket t;
InputStream b;
OutputStream p;
PrintStream pp;
public String name;
public Transaction(int i, Socket s, SynchList v) throws Exception {
outputs = v;
n = i;
t = s;
b = t.getInputStream();
p = t.getOutputStream();
pp = new PrintStream(p);
outputs.add(pp);
}
public void run() {
Scanner s = new Scanner(b);
name = s.next();
int c;
try {
while (s.hasNext()) {
String it = s.nextLine();
for (int j = 0; j < outputs.size(); j++) {
{
(outputs.get(j)).println(name + ": " + it);
(outputs.get(j)).flush();
}
}
System.out.println(name + ": " + it);
}
System.out.print("Client " + n + " " + name + " left the conversation");
outputs.remove(pp);
} catch (Exception e) {
outputs.remove(pp);
System.out.print(e);
}
}
}
I keep getting this error for the following code, can anyone help?
G:\StringBroadcaster.java:57: error: cannot find symbol
int resultSet = st.executeUpdate(SQLquery);
^
symbol: variable SQLquery
location: class StringBroadcaster
G:\StringBroadcaster.java:63: error: cannot find symbol
SQLquery = "INSERT INTO one (Port,Name,Message) VALUES('a','hello','muhsina')";
^
symbol: variable SQLquery
location: class StringBroadcaster
2 errors
Tool completed with exit code 1)
Thanks.
You have executed the line
int resultSet = st.executeUpdate(SQLquery);
before define the value of variable SQLquery.
You haven't declared a type for your SQLQuery variable (also variables conventionally start with a lowercase letter to distinguish them from class names). So the line below // Execute a query should read:
String SQLquery = "INSERT INTO one (Port,Name,Message) VALUES('a','hello','hii')";
Additionally:
You have a line after this, VALUES(1,'hello','muhsina')");, which is just completely illegal syntax. I'm guessing this was an accidental copy-paste error.
You're using the query variable before you declare it, as others have pointed out. You need to move the st.executeUpdate() call after the point where the query is declared.
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.