getting database info that matches user input
807600Nov 18 2007 — edited Nov 19 2007I am trying to print out only the information from the database that matches the user input. Here is my code so far. I tried Select * from Products where PID = pd and I've tried if statements and can't get it.
.
import java.sql.*;
import java.io.*;
import java.util.Scanner;
public class SelectDataApp
{
Scanner scanner = new Scanner(System.in);
public void selectData()
{
Connection con = null;
try
{
//Load the Driver class file
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String source = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=product.mdb";
con = DriverManager.getConnection(source);
System.out.print("Enter a PID: ");
int pd = scanner.nextInt();
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("select * from Products");
while(rs.next())
{
System.out.println("The info for the PID you chose is:");
// get the PID
System.out.println("PID = " + rs.getInt("PID"));
// get the name
System.out.println("Name = " + rs.getString("Name"));
// get the description
System.out.println("Description = " + rs.getString("Description"));
// get the price
System.out.println("Price = $" + rs.getDouble("Price") + "\n");
}
rs.close();
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
try {
if ( con != null ) {
// Close the connection no matter what
con.close();
}
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
}
}
public static void main(String[] args) {
SelectDataApp myselect = new SelectDataApp();
myselect.selectData();
}
}