Below I am asking the user to enter data, now if the user enters all field of data..then I get what i expect in return. Yet I want the user to be able to enter one value and print the entire row containing that one value the user entered. Now i am trying to use if else statements while the values are empty..but it is not working. Can someone tell me a better way?/ why this is not working?
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSetMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class DbReader
{
public static void main(String[] args)
{
Connection conn = null;
Scanner in= new Scanner(System.in);
String testing = "";
String empty = "";
try
{
Class.forName("com.mysql.jdbc.Driver");//need this for some reason
conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/dealer", "root", "root");
if(conn!=null)
{
System.out.println("connected successfully to database");
}
System.out.println("Please Enter Vehicle Information: ");
System.out.println("Make");
System.out.println("Color");
System.out.println("Model");
System.out.println("Year");
String make = in.next();
String color = in.next();
String model = in.next();
String year = in.next();
//String userInput="FOR";
if(make.equals(empty) && color.equals(empty)&& model.equals(empty)){
testing ="SELECT * FROM cars WHERE year = '"+year+"';";
}
else if(make.equals(empty) && color.equals(empty)&& year.equals(empty)){
testing ="SELECT * FROM cars WHERE year = '"+model+"';";
}
else if(make.equals(empty) && model.equals(empty)&& year.equals(empty)){
testing ="SELECT * FROM cars WHERE year = '"+color+"';";
}
else if(model.equals(empty) && color.equals(empty)&& year.equals(empty)){
testing ="SELECT * FROM cars WHERE year = '"+make+"';";
}
else
testing = "SELECT * FROM cars WHERE make = '" + make+"' AND color = '"+color+"' AND model = '"+model+"' AND year = '"+year+"';";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(testing);//this line causes me to lose connection why?..because i was printing from database not from table
while(rs.next()) {
if(rs.getString("make").equals(make) && rs.getString("color").equals(color))
{
System.out.println(" VIN: "+ rs.getString("vin"));
//System.out.println(" MAKE: ");
System.out.println(" MAKE: "+ rs.getString("make"));
// System.out.println(" MODEL: ");
System.out.println(" MODEL: "+ rs.getString("model"));
//System.out.println(" COLOR: ");
System.out.println(" COLOR: "+ rs.getString("color"));
System.out.println(" PRICE: "+ rs.getString("price"));
}else{
System.out.println(" Sorry No Cars meet that descrption at this time ");
}
}
st.close();
rs.close();
conn.close();
}catch(Exception e)
{
System.out.println("not connected to database");
}
}
}
Aucun commentaire:
Enregistrer un commentaire