JDBC -- not enough values - java

I have a MySQL table, EMPLOYEES, which has the following form:
CREATE TABLE EMPLOYEES
(
FNAME VARCHAR(15) NOT NULL,
LNAME VARCHAR(15) NOT NULL,
PHONE CHAR(10),
HOURS INT NOT NULL,
EMPLOYEE_NUM CHAR(5) NOT NULL,
PRIMARY KEY(EMPLOYEE_NUM)
);
I'm attempting to write a program which allows me to manipulate the table. I have the following method to attempt to do this.
void addEmployee(Connection conn) throws SQLException, IOException {
Statement stmt = conn.createStatement();
String fName = readEntry("First name: ");
String lName = readEntry("Last name: ");
String phoneNumber = readEntry("Phone number: ");
String hours = readEntry("Number of hours worked: ");
String employeeNum = readEntry("Employee Number: ");
String query = "INSERT INTO EMPLOYEES VALUES ('" +
fName + "','" + lName + "','" + phoneNumber + "'," + hours + ",'" + employeeNum + "')";
try {
int nrows = stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println("Error Adding Catalog Entry");
while (e != null) {
System.out.println("Message : " + e.getMessage());
e = e.getNextException();
}
return;
}
stmt.close();
System.out.println("Added Catalog Entry");
}
When I try to execute this call:
First name: fname
Last name: lname
Phone number:
Number of hours worked: 34
Employee Number: 01923
Error Adding Catalog Entry
Message : ORA-00947: not enough values
In this attempt, I left "phoneNumber" blank for NULL. In an earlier attempt I gave it a phone number and got the same message.
Does anyone know why this is happening?
If any crucial information is missing, let me know and I can add it.
Thanks,
erip

When you do an insert, you should always list the columns.
Does this work?
INSERT INTO EMPLOYEES(fname, lname, phoneNumber, hours, employee_Num)
VALUES ('" +fName + "','" + lName + "','" + phoneNumber + "'," + hours + ",'" + employeeNum + "')

Related

inserting to database using java gui

I am trying to insert data from my netbeans to mysql workbench. there is no problem with the query but when I run the program a message box appear "Unknown column 'empJob' in 'field list '" . What seems to be the problem?
and just to Know i tried this on another table and it works just fine! but in this one it doesn't work!
int id, Salary;
String name, Address, Jop;
id = Integer.parseInt(tNo.getText());
name = tName.getText();
Address = tAddress.getText();
Jop = tJop.getText();
Salary = Integer.parseInt(tNo.getText());
String sql = "insert into employee(empid,empName, empAddress,empJob,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int x = st.executeUpdate(sql);
if (x > 0) {
JOptionPane.showMessageDialog(prev, x + "rows effected");
} else {
JOptionPane.showMessageDialog(prev, "insert failed");
}
Do you have a typo? You write empJob -> but your variable is called Jop. So maybe it should be empJop.
String sql = "insert into employee(empid,empName, empAddress,empJop,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";

How do I filter search by entering all the column data on java-sql application?

I've been trying to solve this issue for the past couple of days. I have a SerachUser function where I input all the data like age, gender, city and interests into each string and check them into a select query command.
If data is present, I print them out.
Unfortunately the search isn't working completely. For eg: my table user doesn't have 'F' gender. But if I type 'F' I still get data instead of displaying "ResultSet in empty in Java".
Below is a brief code I have done.
try{
conn = DriverManager.getConnection(DB_URL,"shankarv5815","1807985");
st = conn.createStatement();
rs = st.executeQuery("Select loginID, f_name, l_name from users where gender = '" +
searchUser.getGender() + "' and age between '" + min + "' and '" + max + "' and city = '" +
searchUser.getCity() + "' and interest1 = '" + searchUser.getInterest1() +
"' or interest2 = '" + searchUser.getInterest1() + "' or interest3 = '" +
searchUser.getInterest1() + "' and loginID != '" + curUser + "'");
if (rs.next() == false) {
System.out.println("ResultSet in empty in Java");
}
else {
do {
String id = rs.getString(1);
String fName = rs.getString(2);
String lName = rs.getString(3);
System.out.print(id +" ," + fName + ", " + lName);
System.out.println();
} while (rs.next());
}
}
catch(SQLException e){
e.printStackTrace();
}
finally
{
try
{
conn.close();
st.close();
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
A reduced version of your query is :
Select * from users
Where gender = 'F'
And interest1 = 'FISHING'
Or interest2 = 'FISHING'
However, AND has higher priority than OR, so this query is equivalent to :
Select * from users
Where ( gender = 'F' And interest1 = 'FISHING')
Or interest2 = 'FISHING'
What you need to do is add brackets, so :
Select * from users
Where gender = 'F'
And ( interest1 = 'FISHING' Or interest2 = 'FISHING')
By the way, you are also leaving yourself wide open to a SQL injection attack, by including the search terms directly in the SELECT statement ( see What is SQL injection? ).
Much better would be to get in the habit of always using a PreparedStatement.

SQLITE delete method in Java

I have a method that should delete a Person(a row) from my database.
I am getting the error message that I created in the catch. I just started working with Databases and I have mostly been piecing together different techniques. I'm not sure what to do
public static void deletePerson(String firstNameOfPersonToDelete, String lastNameOfPersonToDelete) {
Statement stmt = null;
try {
// Create database connection
Connection c = DriverManager.getConnection("jdbc:sqlite:PERSON.db");
// Create Statement object
stmt = c.createStatement();
// Get person we're about to delete
String getPersonQuery = "SELECT SSN FIRSTNAME, LASTNAME, AGE, CREDITCARD FROM PERSON WHERE FIRSTNAME = '"
+ firstNameOfPersonToDelete + "' AND LASTNAME = '" + lastNameOfPersonToDelete + "'";
ResultSet rs = stmt.executeQuery(getPersonQuery);
String ssn = rs.getString("SSN");
String firstName = rs.getString("FIRSTNAME");
String lastName = rs.getString("LASTNAME");
String age = rs.getString("AGE");
String creditCard = rs.getString("CREDITCARD");
String deletePersonStatement = "DELETE FROM PERSON WHERE FIRSTNAME = '" + firstName + "' AND LASTNAME = '"
+ lastName + "'";
stmt.executeUpdate(deletePersonStatement);
System.out.println("The following record was deleted:\n" + ssn + "\n" + firstName + " " + lastName + "\n"
+ age + "\n" + creditCard);
System.out.println("\nThe database contains the following records: ");
ArrayList<Object> myPeople = findAllPeople();
for (Object element : myPeople) {
System.out.println(element.toString());
}
} catch (SQLException e) {
e.printStackTrace(System.err);
System.out.println("Error: The person: \"" + firstNameOfPersonToDelete + " " + lastNameOfPersonToDelete
+ "\" was not found. No records were deleted.");
System.out.println("\nThe database contains the following records: ");
ArrayList<Object> myPeople = findAllPeople();
for (Object element : myPeople) {
System.out.println(element.toString());
}
}
}
java.sql.SQLException: no such column: 'SSN'Error: The person: "Fitzgerald Grant" was not found. No records were deleted.
at org.sqlite.jdbc3.JDBC3ResultSet.findColumn(JDBC3ResultSet.java:48)
at org.sqlite.jdbc3.JDBC3ResultSet.getString(JDBC3ResultSet.java:443)
at Test.deletePerson(Test.java:181)
at Test.main(Test.java:65)
SELECT SSN FIRSTNAME, LASTNAME, AGE, CREDITCARD FROM ...
^
This is the same as SSN AS FIRSTNAME, i.e., in the output of the query, the SSN column is renamed to FIRSTNAME. You apparently forgot a comma.
In any case, you got this error because there is no SSN column.
You have to ensure that you create this table with this column, or if you have an old database, that you add this column.

Unable to retrieve first column

I am trying to get the first column (column id and get the associated first and last name). I have tried multiple things but unable to get it to work.
It returns me with error CUSTOMERID not found.
public String getCustomerUsingId(int id) {
String firstName = null;
String lastName = null;
Statement stmt = null;
String getCustomerQuery = "SELECT FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
+ id + "'";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
stmt.execute(getCustomerQuery);
ResultSet rs = stmt.getResultSet();
if(rs.next()){
id = rs.getInt("CUSTOMERID");
System.out.println("id is:" + id);
if(id == -1){
System.out.println("value is true");
firstName = rs.getString(2);
lastName = rs.getString(3);
System.out.println("First Name :" + firstName);
System.out.println("First Name :" + lastName);
}
}
}
I am using H2 as database and this is what is looks like
CUSTOMERID FIRSTNAME LASTNAME
1 P S
2 K S
This is how I have created the table
String customerSqlStatement = "CREATE TABLE CUSTOMERS " + "(customerId INTEGER NOT NULL IDENTITY(1,1) PRIMARY KEY, " + " FirstName VARCHAR(255), " + " LastName VARCHAR(255))";
You also need to explicitly include the column name in the select query.
So, the variable getCustomerQuery should be something like
String getCustomerQuery = "SELECT CUSTOMERID,FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
+ id + "'";

MySQLSyntaxErrorException: Unknown column ' ____ ' in 'field list'

I get the following MySQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'book.call_Number' in 'field list'.
What does that mean and how can I solve it?
Here is the code responsible for this exception:
public void actionPerformed(ActionEvent e) {
list.clearSelection();
String selectString = " ";
String afName = auth_fName.getText();
String aMI = auth_MI.getText();
String alName = auth_lName.getText();
String tField = titleField.getText();
String sField = subjectField.getText();
try {
Connection conn = Database.getConnection();
Statement s = conn.createStatement();
if (!afName.equals("") && (!aMI.equals("")) && (!alName.equals("")) && (!tField.equals("")) && (!sField.equals(""))) {
selectString = "SELECT a.call_Number as callNbr "
+ "FROM book a "
+ "FULL JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
}
s = conn.createStatement();
System.out.println(selectString);
ResultSet rs = s.executeQuery(selectString);
while (rs.next()) {
String call_Num = rs.getString("call_Number");
String title = rs.getString("title");
String auth_lName = rs.getString("auth_lName");
String auth_MI = rs.getString ("auth_MI");
String auth_fName = rs.getString("auth_fName");
String availability = rs.getString("availability");
view = new View(call_Num, title, auth_lName, auth_MI, auth_fName, availability);
vList.add(view);
System.out.println(view);
}
rs.close();
s.close();
conn.close();
list.setListData(vList.toArray());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here is the DDL and content:
s.executeUpdate (
"CREATE TABLE book ("
+ "call_Number CHAR(10),"
+ "PRIMARY KEY (call_Number),"
+ "auth_fName CHAR(30)NOT NULL, auth_MI CHAR(2),"
+ "auth_lName CHAR(50)NOT NULL, title CHAR(100) NOT NULL,"
+ "subject CHAR(30) NOT NULL)");
count = s.executeUpdate (
"INSERT INTO book"
+ " VALUES"
+ "('MY.111.000', 'Mark', 'M','Bradshaw','Mystery Under the Sun','mystery'),"
+ "('MY.111.001', 'Mark','','Twain','The Adventures of Huckleberry Finn','mystery'),"
+ "('SF.111.002', 'Kito', 'M','Bradford','Mr. Roboto','science fiction'),"
+ "('SF.111.003', 'Eric','','Laslow','Science Fiction - Can It Happen?','science fiction'),"
+ "('AV.111.004', 'Rashad','','Cheeks','Fire Under the Bridge','adventure'),"
+ "('AV.111.005', 'Samantha','A','Appleby','The Open Sea','adventure'),"
+ "('CO.111.006', 'Lindsey', '','Butterby','What? We cant spend anymore!?','comedy'),"
+ "('CO.111.007', 'Judy', 'S','Yates','So this is life?','comedy'),"
+ "('IN.111.008', 'Elizabeth', 'J','Lee','Mystery Under the Sun','international'),"
+ "('IN.111.009', 'Gabriella', 'M','Rodriguez','Love in Brazil','international')");
*******t_action table***************************
//create transaction table
s.executeUpdate (
"CREATE TABLE t_action ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "avail CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO t_action"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-03-08','2011-03-15','AVAILABLE',5.00),"
+ "('P222200001','MY.111.001','2011-03-31','2011-04-6','DUE 2011-04-6',5.00),"
+ "('P222200002','SF.111.002','2011-03-30','2011-04-5','DUE 2011-04-5',5.00),"
+ "('P222200003','SF.111.003','2011-03-29','2011-04-4','DUE 2011-04-4',5.00),"
+ "('P222200004','AV.111.004','2011-03-28','2011-04-3','DUE 2011-04-3',5.00),"
+ "('P222200005','AV.111.005','2011-03-27','2011-04-2','DUE 2011-04-2',5.00),"
+ "('P222200006','CO.111.006','2011-03-26','2011-04-1','DUE 2011-04-1',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','AVAILABLE',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','AVAILABLE',5.00),"
+ "('P222200009','IN.111.009','2011-03-06','2011-03-12','AVAILABLE',5.00)");
Use a <column> as predicate like below:-
selectString = "SELECT a.call_Number as callNbr, ... "
+ "FROM book a"
+ "FULL JOIN transaction b"
+ "ON a.call_Number=b.call_Number";
And then change the code to look for callNbr :-
String call_Num = rs.getString("callNbr");
HTH.
Change your query to this:
selectString = "SELECT a.call_Number "
+ "FROM book a "
+ "INNER JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
MySQL does not support FULL OUTER JOIN. If you really need the effect of that - you'll need 2 selects with a UNION. Although from looks of it - does not seem like that would be necessary.

Categories

Resources