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();
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 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(" ) ");
I am currently trying to scan and parse the file that is not in sql format. I am trying to input all the data into the SQL table but for some reason every time i run the program, i get the error saying unknown column 'what' in 'field list.' So the neither of the data goes through. 'what' is one of the names that is on the text. The table currently has 11 columns. I know I am parsing or scanning it wrong but I cannot figure out where. Here is my code:
public class parseTable {
public parseTable (String name) throws FileNotFoundException
{
File file = new File(name);
parse(file);
}
private void parse(File file) throws FileNotFoundException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/";
String connectionUser = "";
String connectionPassword = "";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
String query = "";
for(int i = 0; i < rowInfo.length; i++)
{
if(query.equals(""))
{
query = rowInfo[i];
}
else if(i == 9){
query = query + "," + rowInfo[i];
}
else if(rowInfo[i].equals(null)){
query = query + ", " + "NULL";
}
else
query = query + ", " + "'" + rowInfo[i] + "'";
}
stmt.executeUpdate("INSERT INTO dup VALUES(" + query + ")");
count = 0;
rowInfo = new String[11];
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
And this is the data I'm trying to input:
1 hello cheese 1111 what#yahoo.com user adm street zip what USA
2 Alex cheese 1111 what#yahoo.com user adm street zip what USA
So this is my new code now, using PrepareStatement. However I still get an error and I looked online for the solution on where I'm making a mistake, but I cant seem to figure out where.
String query = "INSERT INTO mil_table (UserName, NameFirst, NameLast, supportID, EmailAddress, Password,
IDQ, AddressCity, AddressState, AddressZip, AddressCountry) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(query);
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
for(int i = 0; i <rowInfo.length; i++)
{
pstmt.setString(i + 1, rowInfo[i]);
}
//stmt.executeUpdate("INSERT INTO mil_table VALUES(" + query + ")");
//System.out.println("#" + query + "#");
pstmt.executeUpdate();
count = 0;
rowInfo = new String[11];
}
}
As you are using MySQL, you will need to enclose the text inputs with quotes. Try enclosing the String values that you are inserting in quotes and then execute your code.
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 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.