简体   繁体   中英

Java JDBC throwing an error for an SQL query asking to return details from only particular rows

I have a database called 'airplane' inside which there is a table named booking. The booking table has the columns phone(int type) ,name(text type),address(text type),city(text type) destination(text type),date(text type). I want to fetch only the rows whose phone column has value or data equal to phone number entered by the user . I wrote the following code for it . For context , I am using java using JDBC

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/airplane";
static final String USER = "root";
static final String PASS = "";

Connection conn = null;



try
  {
    System.out.println("enter cell no");
    int cell=sc.nextInt();
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    System.out.println("Connected database successfully...");

   // My SQL SELECT query.

    String query = "SELECT * FROM `booking` where phone=cell";

   // creating the java statement
   Statement st = conn.createStatement();

   /** executing the query, and getting a java resultset of all rows whose phone
    column has the value equal to one entered by user and stored by me in 
  int variable cell**/

   ResultSet rs = st.executeQuery(query);

         //iterate through the java resultset
         while (rs.next())
           {
            int Phone = rs.getInt("phone");
            String Name = rs.getString("name");
            String Address = rs.getString("address");
            String City = rs.getString("city");
            String Destination = rs.getString("destination");
            String Date = rs.getString("date");

// print the results
           System.out.format("%d, %s, %s, %s, %s, %s\n", Phone, Name, Address, City, Destination, Date);
                       }

                        st.close();
                    }
                    catch (Exception e)
                    {
                        System.err.println("Got an exception! ");
                        System.err.println(e.getMessage());
                    }

I am getting the error:

Got an exception! 
Unknown column 'cell' in 'where clause'

What am I doing wrong?

Try this:

String query = "SELECT * FROM `booking` where phone=" + cell;

A better way to handle this is to use PreparedStatement

This case, the query would look like:

String query = "SELECT * FROM `booking` where phone=?"

and

statement.setInt(1, cell);

you will see it's gonna run

String query = "SELECT * FROM booking where phone="+"\\"%s\\"";

query=String.format(query,cell);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM