【问题标题】:Java JDBC throwing an error for an SQL query asking to return details from only particular rowsJava JDBC 对要求仅从特定行返回详细信息的 SQL 查询抛出错误
【发布时间】:2019-03-25 13:28:34
【问题描述】:

我有一个名为“飞机”的数据库,其中有一个名为 booking 的表。 预订表具有列电话(int 类型)、名称(文本类型)、地址(文本类型)、城市(文本类型)目的地(文本类型)、日期(文本类型)。我只想获取其电话列的值或数据等于用户输入的电话号码的行。我为它编写了以下代码。对于上下文,我使用 JDBC 使用 java

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());
                    }

我收到错误:

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

我做错了什么?

【问题讨论】:

    标签: java mysql jdbc xampp


    【解决方案1】:

    试试这个:

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

    处理这个问题的更好方法是使用PreparedStatement

    在这种情况下,查询将如下所示:

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

    statement.setInt(1, cell);
    

    【讨论】:

      【解决方案2】:

      你会看到它会运行

      字符串查询 = "SELECT * FROM booking where phone="+"\"%s\"";

      query=String.format(query,cell);

      【讨论】:

      • 最好养成使用 PreparedStatement 的习惯。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2023-02-07
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多