так что я получаю ошибку. Вот мой вывод, когда я запускаю эту программу и выбираю запрос 1:
Connecting to the database...
The database connection was successful
Menu
Choose from the following:
1. Add a new author
2. Edit an existing author
3. Add a new Title
4. Add a new Author/Title combination
5. Print databases
6. Exit
Make selection :
1
Enter author first name:
oodewrw
Enter author last name:
asfsdf
Running query:
Creating statement...
SQL Error Message 1: ORA-00984: column not allowed here
Menu
Choose from the following:
1. Add a new author
2. Edit an existing author
3. Add a new Title
4. Add a new Author/Title combination
5. Print databases
6. Exit
Make selection :
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ConnectAndRunQueries.getInput(ConnectAndRunQueries.java:154)
at ConnectAndRunQueries.driver(ConnectAndRunQueries.java:94)
at ConnectAndRunQueries.main(ConnectAndRunQueries.java:69)
Игнорируя, что я также получаю нулевой указатель исключения, я запутался в том, почему я получаю ошибку столбца. Из того, что я могу сказать, Oracle обычно думает, что все, что не в кавычках, является столбцом. Но так как это Java-программа, я использую переменные вместо строк, поэтому я не хочу помещать их в кавычки.
Другие вещи, которые я пробовал : использование всех заглавных букв в моей программе, игра с конкатенацией, все равно добавление переменных в кавычки, добавление числа и полная вставка вместо частичной вставки, подключение вручную в SQLPLUS и введите "INSERT INTO Authors VALUES <'Me', 'Julie'>; (я получаю обратно" одна строка создана ".)
Почему моя программа видит переменные как вставку столбца?
Вот мой код:
import java.sql.*;
import java.util.Scanner;
public class ConnectAndRunQueries {
private final static String dbURL = "jdbc:oracle:thin:@coisor.austincc.edu:1527:CSOR";
private final static String dbUser = "user";
private final static String dbPasswd = "password";
Connection connection = null;
Statement statement = null;
public int choice = 0;
public String firstName;
public String lastName;
public int authorID;
public int ISBN;
public String title;
public int editionNumber;
public String copyright;
public Boolean quit = false;
public ResultSet resultSet = null;
public Boolean weAreOkay = false;
public String query = null;
public int numberOfColumns = 0;
public static void main(String args[]) throws Exception
{
try {
// Load the driver class
Class.forName("oracle.jdbc.OracleDriver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
return;
}
catch(Exception e) {
System.out.println("Failed to load SQL driver." + e);
return;
}
ConnectAndRunQueries myObject = new ConnectAndRunQueries();
myObject.driver();
}
public void driver() throws Exception
{
System.out.println("\nConnecting to the database...");
testConnectToDb();
getInput();
while (!quit)
{
createQueries();
System.out.println("Running query:");
runQueries(query);
if (choice == 5)
{
displayQueries();
choice = 5;
createQueries();
runQueries(query);
}
getInput();
}
System.out.println("Closing the Database Connection...");
closeDBConnection();
}
private boolean testConnectToDb()
{
boolean rtnCode = false;
try {
connection = DriverManager.getConnection(dbURL, dbUser, dbPasswd);
if(connection != null)
{
rtnCode = true;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
if (rtnCode)
System.out.println("The database connection was successful");
else
System.out.println("The database connection was Not successful");
return rtnCode;
}
// Close the Database connection.
private void closeDBConnection() throws Exception, SQLException
{
try
{
if (statement != null)
statement.close();
if (connection != null)
connection.close(); // Close the database connection
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void getInput()
{
Scanner input = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
System.out.println("Menu");
System.out.println("Choose from the following:");
System.out.println(" 1. Add a new author");
System.out.println(" 2. Edit an existing author");
System.out.println(" 3. Add a new Title");
System.out.println(" 4. Add a new Author/Title combination");
System.out.println(" 5. Print databases");
System.out.println(" 6. Exit");
System.out.println(" Make selection : ");
Integer input1 = scanner.nextInt();
//scanner.close();
if (input1 == 1)
{
System.out.println(" Enter author first name: ");
firstName = input.nextLine();
System.out.println(" Enter author last name: ");
lastName = input.nextLine();
choice = 1;
input.close();
}
if (input1 == 2)
{
System.out.println(" Enter authorID: ");
authorID = input.nextInt();
System.out.println(" Enter author first name: ");
firstName = input.nextLine();
input.nextLine();
System.out.println(" Enter author last name: ");
lastName = input.nextLine();
choice = 2;
input.close();
}
if (input1 == 3)
{
System.out.println(" Enter ISBN number: ");
ISBN = input.nextInt();
System.out.println(" Enter Title: ");
title = input.nextLine();
input.nextLine();
System.out.println(" Enter Edition Number: ");
editionNumber = input.nextInt();
System.out.println(" Enter Copyright year: ");
copyright = scanner.nextLine();
input.nextLine();
System.out.println(" Enter authorID: ");
authorID = scanner.nextInt();
choice = 3;
input.close();
}
if (input1 == 4)
{
System.out.println(" Enter authorID: ");
authorID = scanner.nextInt();
System.out.println(" Enter ISBN number: ");
ISBN = scanner.nextInt();
choice = 4;
input.close();
}
if (input1 == 5)
{
choice = 5;
}
if (input1 == 6)
{
quit = true;
}
return;
}
private void createQueries()
{
//INSERT INTO Authors
if (choice == 1)
{
query = "INSERT INTO Authors (FirstName, LastName)" + "VALUES (firstName, lastName) ";
}
//UPDATE authors
if (choice == 2)
{
query = "UPDATE Authors " +
" SET FirstName = firstName, LastName = lastName " +
" WHERE AuthorID = authorID) ";
}
//INSERT title
if (choice == 3)
{
query = "INSERT INTO Titles (ISBN, Title, EditionNumber, Copyright)" +
" VALUES (ISBN, title, editionNumber, copyright) ";
}
//INSERT INTO AuthorISBN
if (choice == 4)
{
query = "INSERT INTO AuthorISBN (AuthorID, ISBN)" +
" VALUES (authorID, ISBN) ";
}
if (choice == 5)
{
query = "SELECT AuthorID, FirstName, LastName FROM Authors";
}
if (choice == 6)
{
query = "SELECT ISBN, Title, EditionNumber, Copyright FROM Titles";
}
}
private void runQueries(String queryToRun)throws Exception, SQLException
{
String sqlMessage = null;
// Execute the query and get our result
try {
System.out.println("Creating statement...");
statement = connection.createStatement();
resultSet = statement.executeQuery(queryToRun);
}
catch (SQLException e)
{
if (e != null)
sqlMessage = e.getMessage();
System.out.println("SQL Error Message 1: " + sqlMessage);
return;
}
try {
// process query results
ResultSetMetaData metaData = resultSet.getMetaData();
numberOfColumns = metaData.getColumnCount();
System.out.println("Table of Books Database:\n");
// display row set header
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-8s\t", metaData.getColumnName(i));
System.out.println();
// display each row
while (resultSet.next())
{
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-8s\t", resultSet.getObject(i));
System.out.println();
}
}
catch (SQLException e)
{
weAreOkay = false;
if (e != null)
sqlMessage = e.getMessage();
System.out.println("SQL Error Message 2: " + sqlMessage);
e.printStackTrace();
}
}
public void displayQueries() throws Exception, SQLException
{
String sqlMessage = null;
ResultSetMetaData metaData;
try
{
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println("");
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-16s\t", metaData.getColumnName(i),"%n");
while (resultSet.next() && weAreOkay)
{
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-16s\t", resultSet.getObject(i));
System.out.println();
}
}
catch (SQLException e)
{
weAreOkay = false;
if (e != null) sqlMessage = e.getMessage();
System.out.println("SQL Error Message 2: " + sqlMessage);
e.printStackTrace();
}
}
}