Hi all,
(Firstly please note I am a beginner programmer!).
I have the following code where I am trying to print the data base entries, then the user press the space bar to add another entry, followed by the data base contents being printed again.
Any pointers in the right direction would be great!
import java.sql.*;
import java.util.Scanner;
public class Q1
{
public static void main(String[] args)
{
Connection connection = null;
Statement statement = null;
ResultSet results = null;
Scanner keyboard = new Scanner(System.in);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection(
"jdbc:odbc:Finances","","");
}
catch(ClassNotFoundException cnfEx)
{
System.out.println("* Unable to load driver! *");
System.exit(1);
}
catch(SQLException sqlEx)
{
System.out.println(
"* Cannot connect to database! *");
System.exit(1);
}
finally
{
try
{
connection.close();
}
catch(SQLException sqlEx)
{
System.out.println("* Unable to disconnect! *");
}
}
processResults();
System.out.print("Old Data.");
System.out.print("\n\nPress 'Enter' to add an entry.");
keyboard.nextLine();
String insert = "INSERT INTO Accounts"
+ "VALUES(112233,'SMITH',"
+ "'John James',752.85)";
int result = statement.executeUpdate(insert);
processResults();
System.out.print("New Data.");
}
public static void processResults()
{
Connection connection = null;
Statement statement = null;
ResultSet results = null;
try
{
statement = connection.createStatement();
results = statement.executeQuery(
"SELECT * FROM Accounts");
}
catch(SQLException sqlEx)
{
System.out.println("* Cannot execute query! *");
System.exit(1);
}
try
{
while (results.next())
{
System.out.println();
System.out.println("Account no. "
+ results.getInt(1));
System.out.println("Account holder: "
+ results.getString(3)
+ " " + results.getString(2));
System.out.printf("Balance: %.2f %n%n",
results.getFloat(4));
}
}
catch(SQLException sqlEx)
{
System.out.println("* Error retrieving data! *");
System.exit(1);
}
}
}
Much appreciated :)