I'm new to creating Java programs with a DB connection. I'm trying to get the program to create a table, read a table in so that I can then have queries run and show certain data. From what I can tell I have my program connecting to the DB successfully but I'm receiving the error:
Syntax error: Encountered ")" at line 8, column 1.
Schema 'TEST' does not exist
Schema 'TEST' does not exist
Schema 'TEST' does not exist
Schema 'TEST' does not exist
Other errors, I'm used to receiving the line # so that I at least know where to start looking. With a line and column #, I'm not sure and I have looked through other posts and tried to make the updates like making APP the default schema. A helpful push in the right direction as to where to start looking. Once I figure out how to get past this and have the query print, I know I'll be good to go. Thanks for any help offered.
import static java.lang.System.out;
import java.sql.*;
import java.sql.SQLException;
public class AnimalDB1 {
private static final String url = "jdbc:derby://localhost:1527/AnimalDB;create=true;user=test;password=test";
private static final String tableName = "Animal";
private static Connection conn = null;
private static int nextId = 1;
private boolean tablesCreated = false;
private static void createConnection(){
try{
System.out.println("Connecting to Database...");
conn = DriverManager.getConnection(url);
System.out.println("Database Connection Successful\n");
}
catch (SQLException e){}
}
// Increments the ID number for each animal
private void incId(){
AnimalDB1.nextId++;
}
private void animalTable() throws SQLException{
Statement statement = null;
try{
StringBuilder sb = new StringBuilder("");
sb.append("CREATE table Animal (\n");
sb.append("ID INTEGER NOT NULL,\n");
sb.append("AnimalName varchar(15),\n");
sb.append("Char1 varchar(15),\n");
sb.append("Char2 varchar(15),\n");
sb.append("Char3 varchar(15),\n");
sb.append("Char4 varchar(15),\n");
sb.append(")\n");
// Get a statement from the connection so we can execute the query.
statement = conn.createStatement();
statement.executeUpdate(sb.toString());
tablesCreated = true;
} catch (Exception e){
System.out.println(e.getMessage());
} finally {
if(statement != null){
try {
statement.close();
}
catch(Exception e){
System.err.println(e.getMessage());
System.exit(0); // Something is terribly wrong so just quit the program.
}
}
}
}
private void createAnimal (String animalName, String char1, String char2, String char3, String char4){
PreparedStatement pState = null;
try{
String sql = "Insert into Animal values (?,?,?,?,?,?)";
pState = conn.prepareStatement(sql);
pState.setInt(1, nextId);
pState.setString(2, animalName);
pState.setString(3, char1);
pState.setString(4, char2);
pState.setString(5, char3);
pState.setString(6, char3);
pState.executeUpdate();
pState.close();
incId();
}
catch (SQLException e){
System.err.println(e.getMessage());
}
}
private static void closeConnection() {
try {
// Close the connection
if(conn != null){
conn.close();
}
} catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void queryShowAnimals() throws SQLException{
String query = "SELECT * FROM Animal";
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
out.print(rs.getInt(nextId) + " ");
out.print(rs.getString("animalName") + " ");
out.print(rs.getString("char1") + ", ");
out.print(rs.getString("char2") + ", ");
out.print(rs.getString("char3") + ", ");
out.print(rs.getString("char4") + ", ");
}
}catch (SQLException se){}
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
AnimalDB1 db = new AnimalDB1();
AnimalDB1.createConnection();
System.out.println("Welcome to the Animal Database");
System.out.println("The list below shows all of the animals currently "
+ "stored in the database\n");
db.animalTable();
db.createAnimal("Huskie", "White", "Long hair", "Four legs", "Paws");
db.createAnimal("Salmon", "Silver", "Scales", "Fins", "Swims");
db.createAnimal("Crow", "Black", "Feathers", "Claws", "Flies");
db.createAnimal("Black Snake", "Black", "Scales", "No Appendages", "Slithers");
AnimalDB1.queryShowAnimals();
closeConnection();
}
}
There are two typing mistakes:
...
StringBuilder sb = new StringBuilder("");
sb.append("CREATE table Animal (\n");
sb.append("ID INTEGER NOT NULL,\n");
sb.append("AnimalName varchar(15),\n");
sb.append("Char1 varchar(15),\n");
sb.append("Char2 varchar(15),\n");
sb.append("Char3 varchar(15),\n");
sb.append("Char4 varchar(15)\n"); // <-- unnecessary comma
sb.append(")\n");
...
and:
...
while (rs.next()){
out.print(rs.getInt("ID") + " "); // <-- invalid column identifier
out.print(rs.getString("animalName") + " ");
out.print(rs.getString("char1") + ", ");
out.print(rs.getString("char2") + ", ");
out.print(rs.getString("char3") + ", ");
out.print(rs.getString("char4") + ", ");
}
...
Additionally, I believe that you want to use a database embedded. So, you need to load the corresponding driver (optional step since Java 6):
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
And the URL:
jdbc:derby:AnimalDB;create=true;user=test;password=test
Try using String buffer instead and i dont see the point in using \n after every line. Moreover chek u have proper spaces after each " .
StringBuffer sb = new StringBuffer("");
sb.append("CREATE table Animal ( ");
sb.append("ID INTEGER NOT NULL ");
sb.append("AnimalName varchar(15) ");
sb.append("Char1 varchar(15) ");
sb.append("Char2 varchar(15) ");
sb.append("Char3 varchar(15) ");
sb.append("Char4 varchar(15) ");
sb.append(" ) ");
Related
Everytime at around "composedLine = String.format("%s, %s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);"
it produces "INSERT INTO airport VALUES (, ABR, Aberdeen Regional Airport, Aberdeen"
instead of "INSERT INTO airport VALUES (ABR, Aberdeen Regional Airport, Aberdeen"
which causes a syntax error when I use executeupdate due to the "," before the ABR.
import java.io.*;
import java.sql.*;
import java.util.*;
public class UsaDelayFlight {
public static Connection connectToDatabase(String user, String password, String database) {
System.out.println("------ Testing PostgreSQL JDBC Connection ------");
Connection connection = null;
try {
String protocol = "jdbc:postgresql://";
String dbName = "";
String fullURL = protocol + database + dbName + user;
connection = DriverManager.getConnection(fullURL, user, password);
} catch (SQLException e) {
String errorMsg = e.getMessage();
if (errorMsg.contains("authentication failed")) {
System.out.println("ERROR: \tDatabase password is incorrect. Have you changed the password string above?");
System.out.println("\n\tMake sure you are NOT using your university password.\n"
+ "\tYou need to use the password that was emailed to you!");
} else {
System.out.println("Connection failed! Check output console.");
e.printStackTrace();
}
}
return connection;
}
public static void dropTable(Connection connection, String table) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("DROP TABLE IF EXISTS " + table);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static void createTable(Connection connection, String tableDescription) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("CREATE TABLE IF NOT EXISTS " + tableDescription);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static ResultSet executeQuery(Connection connection, String query) {
System.out.println("DEBUG: Executing query...");
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static int insertIntoTableFromFile(Connection connection, String table,
String filename) {
int numRows = 0;
String currentLine = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
Statement st = connection.createStatement();
// Read in each line of the file until we reach the end.
while ((currentLine = br.readLine()) != null) {
String[] values = currentLine.split(",");
System.out.println(Arrays.toString(values));
String composedLine = "INSERT INTO " + table + " VALUES (";
//String r = String.format("formatted values are %s", composedLine);
composedLine = String.format("%s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);
System.out.println(composedLine);
//. . .
// Finally, execute the entire composed line.
numRows = st.executeUpdate(composedLine);
}
} catch (Exception e) {
e.printStackTrace();
}
return numRows;
}
// NOTE: You will need to change some variables from START to END.
public static void main(String[] argv) throws SQLException {
// START
// Enter your username.
String user = "";
// Enter your database password, NOT your university password.
String password = "";
/** IMPORTANT: If you are using NoMachine, you can leave this as it is.
*
* Otherwise, if you are using your OWN COMPUTER with TUNNELLING:
* 1) Delete the original database string and
* 2) Remove the '//' in front of the second database string.
*/
String database = "";
//String database = "";
// END
Connection connection = connectToDatabase(user, password, database);
if (connection != null) {
System.out.println("SUCCESS: You made it!"
+ "\n\t You can now take control of your database!\n");
} else {
System.out.println("ERROR: \tFailed to make connection!");
System.exit(1);
}
// Now we're ready to use the DB. You may add your code below this line.
createTable(connection, "delayedFlights (ID_of_Delayed_Flight varchar(15) not null, Month varchar(10), "
+ "DayofMonth int, DayofWeek int, DepTime timestamp, ScheduledDepTime timestamp, ArrTime int,"
+ "ScheduledArrTime timestamp, UniqueCarrier varchar(15) not null, FlightNum int, ActualFlightTime timestamp,"
+ "scheduledFlightTime timestamp, AirTime timestamp, ArrDelay timestamp, DepDelay timestamp, Orig varchar(15),"
+ "Dest varchar(15), Distance int, primary key (ID_of_Delayed_Flight), unique (UniqueCarrier));");
createTable(connection, "airport (airportCode varchar(15) not null, "
+ "airportName varchar(15), City varchar(15), State varchar(15), primary key (airportCode));");
insertIntoTableFromFile(connection, "airport", "airport");
String query = "SELECT * FROM delayedFlights;";
ResultSet rs = executeQuery(connection, query);
try {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
}
}
This code is a security vulnerability. Specifically, SQL injection. This is not how you do it.
The correct way also solves your problem in passing. Thus, solution: Do it the correct way, solves all your problems.
Correct way:
PreparedStatement ps = con.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)");
ps.setString(1, values[0]);
ps.setString(2, values[1]);
ps.setString(3, values[2]);
ps.setString(4, values[3]);
ps.executeUpdate();
Hello guys how can I check duplicate inputs (adding students) and how to prevent it. It says that when i create a table the inputs that I've been inserting the database is all a duplicate which is obviously not. In line with that how can I detect and check of the inserted input is a duplicate of the previous inputs.This is the first output in my console This is the continuation
Here is my code:
Main.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//import java.sql.Statement;
public class Main {
public static void main (String args[]) throws Exception {
StudentDAO x1= new StudentDAO();
x1.getConnection();
x1.makeTable(); //create Table
x1.addstud("1","Yves Francisco", "2000000001","5","CpE","Male");
x1.addstud("2","Lance Eco", "2000000002","5","CpE","Male");
x1.addstud("3","Karlos Castillo", "2000000003","5","CpE","Male");
x1.addstud("4","Glenn Bordonada", "2000000004","5","ECE","Male");
x1.addstud("5","JM Enriquez", "2000000005","5","ECE","Male");
x1.addstud("6","John Martinez", "2000000006","2","ECE","Male");
x1.addstud("7","Timothy Tolentino", "2000000007","4","IT","Male");
x1.addstud("8","Kyle Dacaymat", "2000000008","3","CpE","Male");
x1.addstud("9","Dom Benedictos", "2000000009","1","IT","Male");
x1.addstud("10","Lance Roque", "2000000010","1","ECE","Male");
x1.addstud("11", "Vegeta", "2000000011", "1", "ME", "Male"); // added Student
//x1.addstud("12", "Vegeta", "2000000011", "1", "ME", "Male"); // pang check if entered input is a duplicate of a field of studName, studNumber, etc.
//x1.delstud(); // delete student
//x1.updstuddb();
x1.showdb();
}
}
StudentDAO.java
//import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//import java.sql.ArrayList;
public class StudentDAO {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void showdb() throws Exception
{
try {
Connection con = getConnection();
String query = "SELECT *FROM studinfo;";
PreparedStatement showstuddb= con.prepareStatement(query);
ResultSet rs = showstuddb.executeQuery();
System.out.println("Showing Database.....................");
System.out.println("============================================================# THE CONTENT OF THE DATABASE #============================================================");
while (rs.next())
{
String idko = rs.getObject(1).toString();
String ngalan = rs.getObject(2).toString();
String numko=rs.getObject(3).toString();
String baitang=rs.getObject(4).toString();
String kurso=rs.getObject(5).toString();
String kasarian=rs.getObject(6).toString();
System.out.println("My ID number is: "+ idko + " Name is: " + ngalan + " Student Number is: " + numko + " Year/Level is: "+ baitang +" Course is: " + kurso + " Sex is: " + kasarian);
}
showstuddb.close();
System.out.println("Nothing follows.....................");
con.close();
}
catch (Exception e)
{
System.out.println("Error on showing contents of database!!!" + e.getMessage());
}
}
public void updstuddb () throws Exception
{
try {
Connection con = getConnection();
String query = "UPDATE studinfo SET studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=? WHERE studid=?";
PreparedStatement studup = con.prepareStatement(query);
studup.setString(1, "Kakarot"); //This will be the replacement
studup.setString(2, "2000000020");
studup.setString(3, "2");
studup.setString(4, "IT");
studup.setString(5, "dafq");
studup.setString(6, "1");// The unique element among the content of the database which is used to determine which is to update
studup.executeUpdate();
System.out.println("THE LIST HAS BEEN UPDATED ############################################################");
studup.close();
con.close();
}
catch (Exception e)
{
System.out.println("Error in updating the database!!!" + e.getMessage());
}
}
public void delstud()
{
try {
Connection con = getConnection();
String query = "DELETE FROM studinfo WHERE studid=?";
PreparedStatement userdel = con.prepareStatement(query);
userdel.setString(1, "12"); // To determine what to delete in the Database
//userdel.setString(1, "2000000002");
//userdel.setString(1, "2000000003");
//userdel.setString(1, "2000000004");
//userdel.setString(1, "2000000005");
//userdel.setString(1, "2000000006");
//userdel.setString(1, "2000000007");
//userdel.setString(1, "2000000008");
//userdel.setString(1, "2000000009");
//userdel.setString(1, "2000000010");
userdel.execute();
userdel.close();
System.out.println("Data is now deleted!!!");
con.close();
}
catch (Exception e)
{
System.out.println("Error!!!. Data is not deleted " + e.getMessage());
}
}
public void addstud(String studid, String studName, String studNum, String studYrLvl, String studKors, String studGender) throws Exception
{
//String var1 = "Yves Francisco";
//String num1 = "2000000001";
//String num2 = "5";
//String var2 = "CpE";
//String var3 = "Male";
try {
Connection con = getConnection();
PreparedStatement posted= con.prepareStatement("INSERT INTO studinfo (studid, studName, studNum, studYrLvl, studKors, studGender) VALUES (?,?,?,?,?,?)");
int y=1;
posted.setString(y++, studid);
posted.setString(y++, studName);
posted.setString(y++, studNum);
posted.setString(y++, studYrLvl);
posted.setString(y++, studKors);
posted.setString(y++, studGender);
posted.executeUpdate(); // Manipulate or Update table
posted.close();
//con.close();
}
catch (Exception e)
{
System.out.println("Error on adding columns!!!" + e.getMessage());
}
finally
{
System.out.println("Insert Successful!");
}
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
ResultSet rs=checkdup.executeQuery();
while (rs.next())
{
boolean dup1=rs.getObject(2).equals(studName);
boolean dup2=rs.getObject(3).equals(studNum);
boolean dup3=rs.getObject(4).equals(studYrLvl);
boolean dup4=rs.getObject(5).equals(studKors);
boolean dup5=rs.getObject(6).equals(studGender);
System.out.println("The name you entered is: " + dup1 + " The student number you entered is: " + dup2 + " The Yr/Lvl you entered: " + dup3 + " The Course you entered: " + dup4 + " The Sex you entered is: " + dup5);
}
con.close();
}
catch (Exception e)
{
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
}
public void makeTable() throws Exception
{
try
{
Connection con= getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS studinfo (studid INT NOT NULL AUTO_INCREMENT PRIMARY KEY, studName varchar(255), studNum varchar(30), studYrLvl varchar(2), studKors varchar(30), studGender varchar(10));");
create.executeUpdate();
System.out.println("TABLE IS CREATED!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
create.close();
con.close();
}
catch (Exception e)
{
System.out.println("Error on creating table!!. Table not created!"+e.getMessage());
}
finally
{
System.out.println("Table created!");
};
}
public Connection getConnection () throws Exception {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String username= "root";
String password = "root";
Class.forName(driver);
Connection conn= DriverManager.getConnection(url, username, password);
System.out.println("You are now Connected!!");
return conn; // Return if it is successfully connected!
}
catch (Exception e)
{
System.out.println("Connection not Established!"+e.getMessage());
}
return null; // Return if unsuccessful
}
}
The problem is not a duplicate value in your table, the problem is that you have a mistake in your code.
I wouldn't do it the way you do, because if you use a Try-Catch, anyway there is a problem or a mistake in your code (looking for duplicates) it will answer that you have a duplicate.
Otherwise, even if you have thousands of duplicates, if you don't get an error you won't get a duplicate.
Anyways, the mistake you have in your code is that you don't give any value to the checkdup prepared statement, you should change it to something like this:
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
checkdup.setString(1, studName);
checkdup.setString(2, studNum);
checkdup.setString(3, studYrLvl);
checkdup.setString(4, studKors);
checkdup.setString(5, studGender);
ResultSet rs=checkdup.executeQuery();
while (rs.next())
{
boolean dup1=rs.getObject(2).equals(studName);
boolean dup2=rs.getObject(3).equals(studNum);
boolean dup3=rs.getObject(4).equals(studYrLvl);
boolean dup4=rs.getObject(5).equals(studKors);
boolean dup5=rs.getObject(6).equals(studGender);
System.out.println("The name you entered is: " + dup1 + " The student number you entered is: " + dup2 + " The Yr/Lvl you entered: " + dup3 + " The Course you entered: " + dup4 + " The Sex you entered is: " + dup5);
}
con.close();
}
catch (Exception e)
{
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
EDIT
There is an easy way to look for duplicates, you just count how many you have like in this code:
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
checkdup.setString(1, studName);
checkdup.setString(2, studNum);
checkdup.setString(3, studYrLvl);
checkdup.setString(4, studKors);
checkdup.setString(5, studGender);
ResultSet rs=checkdup.executeQuery();
int dup=0;
while (rs.next())
{
dup+=1;
}
if (dup>1 ) {
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
con.close();
}
catch (Exception e)
{
System.out.println("There is an error ");
}
In your INSERT statement, you also need to change things. The studid is an autoincrement column, so you don't have to put it in your INSERT. It should be like:
Connection con = getConnection();
PreparedStatement posted= con.prepareStatement("INSERT INTO studinfo (studName, studNum, studYrLvl, studKors, studGender) VALUES (?,?,?,?,?)");
int y=1;
posted.setString(y++, studName);
posted.setString(y++, studNum);
posted.setString(y++, studYrLvl);
posted.setString(y++, studKors);
posted.setString(y++, studGender);
posted.executeUpdate(); // Manipulate or Update table
posted.close();
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 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.
I have tried to write a code that searches a database of students and shows the searched result on a option pane. And I ended up writing the following. The expected result is:
Name: "something"
Roll: "something"
Registration: "Something"
But actually the output is something like this:
Name: null
Roll: null
Registration: null
public class Search
{
JFrame sw = new JFrame("Search Students' Info"); //search window
JTable stable;
JLabel stfl = new JLabel("Roll"); //search text field label
JTextField stf = new JTextField(8); //search text field
JButton sb = new JButton("Search"); //search button
public void exsearch() //Execute Search
{
sw.setLayout(new GridLayout(2,2));
sw.add(stfl);
sw.add(stf);
sw.add(sb);
sw.setSize(200, 100);
sw.setLocation(100, 100);
sw.setVisible(true);
sb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/srsdb";
try
{
Class.forName(driver).newInstance();
java.sql.Connection con = DriverManager.getConnection(url, "root", "");
JOptionPane.showMessageDialog(null, "Connected", "Connection Confirmation", JOptionPane.PLAIN_MESSAGE);
String str ="SELECT* FROM students WHERE Roll="+stf.getText();
java.sql.Statement st = con.createStatement();
java.sql.ResultSet rs = st.executeQuery(str);
rs.first();
int n = rs.getMetaData().getColumnCount();
// String[] columnnNames;
String[] attributes= new String[10];
int j;
while(rs.next())
{
for(j=0; j<3; j++)
{
attributes[j] = rs.getString(j);
}
}
JOptionPane.showMessageDialog(null, "Name :"+attributes[0]+"\nRoll :"+attributes[1]+"\nRegistration :"+attributes[2], "Search Result", JOptionPane.PLAIN_MESSAGE);
}
catch(Exception f)
{
f.printStackTrace();
JOptionPane.showMessageDialog(null, "Not Found", "Search Result", JOptionPane.PLAIN_MESSAGE);
}
}});
}
public static void main (String[] args)
{
new Search();
}
}
I would use a debugger to check which part of your code is omitted.
One wierd thing I see is, that you jump to the first record in your result set:
rs.first();
And then you read the data from all subsequent records in a while loop
while(rs.next())
{
for(j=0; j<3; j++)
{
attributes[j] = rs.getString(j);
}
}
This ensures, that you get the data from the last matching record if there is more than one.
Better would be to check if there is zero or more than one record. If that is the case, issue a warning because probably there is something wrong with your code (use a debugger to find out what).
If there is only one record, read the data from that record and print it (more or less like you try with rs.getString())
Class.forName ensures that the driver class is on the class path, without needing to compile against the class. It loads the class. No instantiation needed.
A PreparedStatement is better against SQL injection.
Column numbers in the SQL API are 1-based: 1, 2, 3, ... A bit of an exception.
When using first the query loop is as follows. You skipped the first row I think.
Do not forget the miscellaneous close().
Better style to list the columns instead of `*'.
Hence:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/srsdb";
try
{
Class.forName(driver);
Connection con = DriverManager.getConnection(url, "root", "");
JOptionPane.showMessageDialog(null, "Connected",
"Connection Confirmation", JOptionPane.PLAIN_MESSAGE);
String str ="SELECT Name, Registration FROM students WHERE Roll=?";
PreparedStatement st = con.createPreparedStatement(str);
String roll = stf.getText();
st.setString(1, roll);
String message = "";
java.sql.ResultSet rs = st.executeQuery();
int recno = 0;
if (rs.first()) {
do {
String name = rs.getString(1);
String registration = rs.getString(2);
++recno;
message += "- " + recno + " -\nName: " + name
+ "\nRoll: " + roll
+ "\nRegistration: " + registration + "\n";
} while (rs.next());
}
rs.close();
JOptionPane.showMessageDialog(null, message, "Search Result",
JOptionPane.PLAIN_MESSAGE);