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.
Related
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.
I try to read data from text file then insert into database but keep getting error.
Below is the code I am writing
Class.forName("org.hsqldb.jdbcDriver");
connection = DriverManager.getConnection("jdbc:hsqldb:TestDB", "sa", "123");
connection.prepareStatement("drop table people if exists;").execute();
connection.prepareStatement("create table people (id integer, name varchar(20) not null, picture varchar(20), detail varchar(40), gender varchar(5), age integer, state varchar(5), primary key(id));").execute();
String fileName = "/Users/da/Desktop/AP Assignment 2/people.txt";
BufferedReader br = new BufferedReader(new FileReader(fileName));
while (strLine != null) {
String data[] = null;
strLine = br.readLine();
data = strLine.split(",");
int id = Integer.parseInt(data[0]);
String name = data[1];
String picture = data[2];
String detail = data[3];
String gender = data[4];
int age = Integer.parseInt(data[5]);
System.out.println(age);
String state = data[6];
String sql = "insert into people(id, name, picture, detail, gender, age, state) values (" + id + "," + name + ", " + picture + ", " + detail + ", " + gender + ", " + age + ", " + state + ")";
connection.prepareStatement(sql).execute();
connection.commit();
}
br.close();
By attempting to embed the data values into your SQL string you have created an SQL Injection problem. For example, the code
int id = 1;
String name = "gord";
String sql = "INSERT INTO people (id, name) VALUES (" + id + ", " + name + ")";
System.out.println(sql);
prints
INSERT INTO people (id, name) VALUES (1, gord)
When we try to execute that statement the query parser recognizes 1 as an integer literal but it interprets gord as a column name, so we'll get a "user lacks privilege or object not found" error.
The solution is to use a parameterized query like this:
int id = 1;
String name = "gord";
String sql = "INSERT INTO people (id, name) VALUES (?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.executeUpdate();
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 + "'";
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 + "')
i have a table - emp_details in mysql
i want to seatch an employ's id number in java.
if it is in the table , then show all the details of employee.
otherwise display an error message.
how i do this
Using JDBC
Here is an example You can build your solution from it.
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
ResultSet rs1=stmt.executeQuery("SELECT * FROM employee_details where Employee_ID='"+strEmpId+"'");
if(rs1.next()) {
System.out.println("Emp ID : " + rs1.getString(1));
System.out.println("Emp Name : " + rs1.getString(2));
System.out.println("Emp Salary : " + rs1.getString(3));
} else {
System.out.println("Emp ID not found");
}
If you want to know more about SQL just go through HERE