[英]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. 我有一个名为“ airplane”的数据库,其中有一个名为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).
预订表包含以下列:电话(int类型),名称(文本类型),地址(文本类型),城市(文本类型),目的地(文本类型),日期(文本类型)。 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
对于上下文,我使用的是使用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());
}
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 处理此问题的更好方法是使用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\\""; 字符串查询=“ SELECT * FROM
booking
,其中phone =” +“ \\”%s \\“”;
query=String.format(query,cell); 查询=的String.format(查询,细胞);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.