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 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.
So I am trying to figure out this assignment and I can not move on in it until I figure this out.
Im a super newb here this is my first java experience, so heads up there. I'm going to attempt to explain this best as I can.
This is how my code is right now
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String name, returning, type, qty, total;
String nameOutputMsg, customerName, returnOutputMsg, customerReturn, typeOutputMsg, typeReturn, qtyOutputMsg, qtyReturn, totalOutputMsg, totalCost, greetingOutputMsg;
name = br.readLine();
returning = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
I'm getting one error and one warning. The warning is " outputMsg can not be resolved to a variable. So I've tried several things, first thought was hey I need to add that to my string list at the top. So I did, now that error has gone away, BUT 5 more have appeared and one warning. The errors are now "the local variable customerName may not have been initialized" This error is repeated for customerReturn, typeReturn, qtyReturn, totalCost. And the warning is resource leak: 'br' is never closed. SO at this point I change the code to look like this:
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String name, returning, type, qty, total;
String nameOutputMsg, returnOutputMsg, typeOutputMsg, qtyOutputMsg, totalOutputMsg, greetingOutputMsg, outputMsg;
String customerName = null;
String customerReturn = null;
String typeReturn = null;
String qtyReturn = null;
String totalCost = null;
name = br.readLine();
returning = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
NOW i have more warnings that appeared
The BR one is still there, then these have been added : "the value of the locl variable outputMsg is not used" and
"Multiple Markers at this line
-The value of the local variable name is not used" and this repears for name, qty, total, returning and type. Here is my complete code if needed
import javax.swing.JOptionPane;
import java.io.*;
public class ThinkGeekPhase1 {
public static void main(String[] args) {
// declare variables
String openingMsg, nameInputMsg, customerName, returnInputMsg, customerReturn,
typeInputMsg, typeReturn, qtyInputMsg, qtyReturn;
double cost = 9.99;
double salesTaxRate = .075;
double totalCost = 0;
int qty;
try
{
// display opening message
openingMsg = "*** Welcome to ThinkGeek Online Ordering System ***\n"
+ " It's a great day to purchase fun geeky items!!";
JOptionPane.showMessageDialog(null, openingMsg);
// get required input using dialogs
nameInputMsg = "Please enter your name: ";
customerName = getStringInput(nameInputMsg);
returnInputMsg = "Are you a returning customer (yes or no)? ";
customerReturn = getStringInput(returnInputMsg);
typeInputMsg = "What type of stocking would you like? (Alien, Cat, Bunny, Devil)";
typeReturn = getStringInput(typeInputMsg);
qtyInputMsg = "How many stockings would you like?";
qtyReturn = getStringInput(qtyInputMsg);
qty = Integer.parseInt(qtyReturn);
totalCost = totalCost(qty, cost, salesTaxRate);
//write data
writeOrderFile(customerName, customerReturn, typeReturn, qty, totalCost);
//read data
confirmation();
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
System.exit(1);
}
}
public static String getStringInput(String prompt) throws Exception
{
String inputValue;
int count =1;
do
{
inputValue = JOptionPane.showInputDialog(prompt);
count++;
if (inputValue == null) //User Pressed Cancel Button.
{
throw new Exception("Cancel Button Pressed, Program closing");
}
if (inputValue.equals(""))
{
JOptionPane.showMessageDialog(null,"Form was blank, try again.");
}
} while (inputValue.equals("") && count < 4);
if (inputValue.equals(""))
{
throw new Exception("Form was blank for three attempts.");
}
return inputValue;
}
public static double totalCost(int number, double cost, double salesTaxRate)
{
double total = 0;
total = (number * cost) * (salesTaxRate + 1);
return total;
}
public static void writeOrderFile(String name, String returning, String type, int qty, double total) throws Exception
{
File file = new File("order.txt");
PrintWriter pw = new PrintWriter(file);
pw.println(name);
pw.println(returning);
pw.println(type);
pw.println(qty);
pw.println(total);
pw.close();
}
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String name, returning, type, qty, total;
String nameOutputMsg, returnOutputMsg, typeOutputMsg, qtyOutputMsg, totalOutputMsg, greetingOutputMsg, outputMsg;
String customerName = null;
String customerReturn = null;
String typeReturn = null;
String qtyReturn = null;
String totalCost = null;
name = br.readLine();
returning = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
}
When I run the program, it terminates right after asking how many stockings I want.
Ok I edited to this
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String nameOutputMsg, returnOutputMsg, typeOutputMsg, qtyOutputMsg, totalOutputMsg, greetingOutputMsg, outputMsg;
String customerName = null;
String customerReturn = null;
String typeReturn = null;
String qtyReturn = null;
String totalCost = null;
nameOutputMsg = br.readLine();
returnOutputMsg = br.readLine();
typeOutputMsg = br.readLine();
qtyOutputMsg = br.readLine();
totalOutputMsg = br.readLine();
outputMsg =br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
It's still saying I'm not using outputMsg though and I"m not sure why, cause It's used right there at then end?
You are setting things incorrectly. It says that the value of your variables are never used because you set them and then never touch them again. Also, customerName, customerReturn, typeReturn, etc. are not the variables you set the values to. You need to use name, type, etc.
Basically, make sure you are using the correct variables in your output messages and that should get rid of your uninitialized warnings.
Your "never used" warnings are because you are setting values to variables and then not using the variables for anything else.
EDIT:
You are now overwriting your OutputMsg strings which makes the br.readLine() useless.
You should do the following:
name = br.readLine();
customerReturn = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + name + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + type + ".\n";
qtyOutputMsg ="You are buying " + qty + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + total + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
System.out.println(outputMsg);
And the warning is resource leak: 'br' is never closed.
See this article about closing streams to remove memory/resource leeks.
"the value of the locl variable outputMsg is not used" and "Multiple
Markers at this line -The value of the local variable name is not
used" and this repears for name, qty, total, returning and type.
You are assigning an object to those variables, but never using the variables for anything. The compiler is alerting you that you could simply remove them from the code and it would not change the functionality.
Im loosing on append method.
I have a program that inputs an information then printing in a text file.
The problem is, I want to append the new input of information into text file too without overwriting, it means that if I rerun the program the information that I encoded will be in the textfile together with the encoded on the last run of the program.
Please help me. Here is the program:
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
System.out.println("STUDENT INFORMATION");
System.out.println("-------------------");
System.out.println("Full Name : ");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("\nCourse and Year : ");
String yearcourse = sc.nextLine();
System.out.println("\nStudent Number : ");
String studentnumber = sc.nextLine();
System.out.println("\nE-mail Address : ");
String eadd = sc.nextLine();
System.out.println("\nCellphone Number : ");
String cpnumber = sc.nextLine();
System.out.println("\nGender : ");
String gender = sc.nextLine();
System.out.println("\nAge : ");
String age = sc.nextLine();
System.out.println("\nDate of Birth : ");
String dob = sc.nextLine();
System.out.println("\nCivil Status : ");
String status = sc.nextLine();
System.out.println("\nAddress : ");
String address = sc.nextLine();
System.out.println("\n\n________________________________________________");
System.out.println("STUDENT INFORMATION");
System.out.println("\nName : " + name + "");
System.out.println("Year and Course : " + yearcourse + "");
System.out.println("Student Number : " + studentnumber + "");
System.out.println("E-mail Address : " + eadd + "");
System.out.println("Cellphone Number : " + cpnumber + "");
System.out.println("Gender : " + gender + "");
System.out.println("Age : " + age + "");
System.out.println("Date of Birth : " + dob + "");
System.out.println("Civil Status : " + status + "");
System.out.println("Address : " + address + "");
System.out.println("");
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try (PrintWriter writer = new PrintWriter(file)){
BufferedWriter bufferWritter = new BufferedWriter(writer);
writer.println("\nSTUDENT INFORMATION:");
writer.println("--------------------");
writer.println("Name : " + name + "");
writer.println("Year and Course : " + yearcourse + "");
writer.println("Student Number : " + studentnumber + "");
writer.println("E-mail Address : " + eadd + "");
writer.println("Cellphone Number : " + cpnumber + "");
writer.println("Gender : " + gender + "");
writer.println("Age : " + age + "");
writer.println("Date of Birth : " + dob + "");
writer.println("Civil Status : " + status + "");
writer.println("Address : " + address + "");
writer.flush();
}
}
}
In this. if I rerun the program, the text file will just overwrite with the new encoded information. They said to use append bufferwriter. but I'm really lost.
Try to change your code to something like this:
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println("\nSTUDENT INFORMATION:");
out.println("--------------------");
out.println("Name : " + name + "");
out.println("Year and Course : " + yearcourse + "");
out.println("Student Number : " + studentnumber + "");
out.println("E-mail Address : " + eadd + "");
out.println("Cellphone Number : " + cpnumber + "");
out.println("Gender : " + gender + "");
out.println("Age : " + age + "");
out.println("Date of Birth : " + dob + "");
out.println("Civil Status : " + status + "");
out.println("Address : " + address + "");
}catch (IOException e) {
// Handle IO exception.
}
This part of the code:
new FileWriter(file,true)
tells it to append when it's set to true, as you can see on the docs.
Or you could change your line:
PrintWriter writer = new PrintWriter(file);
To this:
PrintWriter writer = new PrintWriter(new FileWriter(file,true));
instead of this
PrintWriter writer = new PrintWriter(file);
try this
PrintWriter writer= new PrintWriter(new BufferedWriter(new FileWriter(file, true));
See Also
How to append content to file in Java
How to append text to an existing file in Java
This is what i need to create.
I have a web site where the user can come and design an application form according to their need/requirement. Basically there is a HTML designer available in the website to perform this action. The user can drag and drop HTML components which in turn creates an application form in pure HTML. For example, for creating the "Personal Section" the user can drag & drop the label component and TextBox component and put the label text as "FirstName" and so on. I need to have a database created according to the form the one user has created. If he created the personal section with only FirstName and LastName the table created should have only those two cols. (ie, its up to the user to decide on col name at the time of form creation, the SQL queries for inserting and Updating DB fields all should perform dynamically). Please help me to solve this issue. Any suggested pattern there to apply? (The web application is created using Java)
Any help will be appreciated greatly
Thanks
You may need to code for some sort of form builder which builds the form on the fly and can take help from following code to create dynamic sql tables. This is just a hint not the perfect solution for your problem
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "123");
Statement st = con.createStatement();
System.out.println("connection has been made ");
Scanner scanner = new Scanner(System.in);
System.out.println("please enter table name ");
String tableName = scanner.next();
String strr = null;
System.out.println("Enter no of columns you like to use: ");
int noc = scanner.nextInt();
for (int i = 1; i <= noc; i++) {
BufferedReader bf = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter column name with type ");
String s1 = bf.readLine();
if (strr == null) {
strr = s1;
} else {
strr = strr + s1;
}
}
st.executeUpdate("create table " + tableName + "(" + strr + ")");
System.out.println("your table " + tableName
+ " has been created!!!");
ResultSet rs = st.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
System.out.println("Number of Columns of your table =" + tableName
+ " " + NumOfCol);
System.out.println("Column names are ");
for (int i = 1; i <= NumOfCol; i++) {
System.out.println(rsmd.getColumnName(i));
}
String strn = null;
System.out.println("please enter values you need to insert");
for (int i = 1; i <= NumOfCol; i++) {
String s5 = scanner.next();
if (strn == null) {
strn = s5;
} else
strn = strn + s5;
}
System.out.println(strn);
st.executeUpdate("insert into " + tableName + " values" + "("
+ strn + ")");
System.out.println("your table " + tableName
+ " has been filled!!!");
con.close();
System.out.println("connection has been colsed ");
}
catch (Exception e) {
System.out.println(e.getMessage());
}