有一个名为airplane的MySQL数据库。里面有一张名为“时间表”的表。这张表用于存储飞机公司的航班时刻表
它有五列名为id(int),fromcity(text),tocity(text),seatleft(text)(int)和date。
此表已填写各种航班计划详细信息。
我想检查用户在预订机票时输入的起始城市和目的地城市是否存在。
int test=0;
System.out.println("Enter your Phone number:");
phone[i] = sc.nextInt();
sc.nextLine();
System.out.println("Enter your name:");
name[i] = sc.nextLine();
System.out.println("Enter your address:");
address[i] = sc.nextLine();
System.out.println("Enter your Pick up city:");
city[i] = sc.nextLine();
System.out.println("Enter your Destination:");
destination[i] = sc.nextLine();
System.out.println("Enter your date of travel:");
date[i] = sc.nextLine();
Connection conn = null;
PreparedStatement stmt = null;
Connection conx=null;
try {
String query1 = "SELECT * FROM `booking` WHERE fromcity="+city[i]+"AND tocity="+destination[i];
conx = DriverManager.getConnection(DB_URL, USER, PASS);
Statement st4 = conn.createStatement();
ResultSet rst = st4.executeQuery(query1);
//iterate through the java resultset
while (rst.next())
{
test=test+1;
}
if(test==0)
{
System.out.println("no such flight route exists");
}
st4.close();
}//try closed here
catch(Exception e)
{
System.out.println("got an error");
}
发布于 2018-10-22 13:54:45
是不是要查询的表名为“时间表”而不是“预订”?
此外应该使用参数化查询为SQL查询添加一些安全性。只是将变量连接到查询字符串是不好的做法。
发布于 2018-10-22 15:02:26
将SQL更改为:
String query1 = "SELECT * FROM `booking` WHERE fromcity='"+city[i]+"' AND tocity='"+destination[i]+"';";
我在值和撇号之间包含了间距,因为语句无法编译。我假定city[i]
和destination[i]
是TEXT
或VARCHAR
。
https://stackoverflow.com/questions/-100002955
复制相似问题