首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何解决JAVA程序中的SQL查询使用JDBC在尝试执行SELECT操作时抛出错误?

如何解决JAVA程序中的SQL查询使用JDBC在尝试执行SELECT操作时抛出错误?
EN

Stack Overflow用户
提问于 2018-10-22 05:27:04
回答 2查看 0关注 0票数 0

有一个名为airplane的MySQL数据库。里面有一张名为“时间表”的表。这张表用于存储飞机公司的航班时刻表

它有五列名为id(int),fromcity(text),tocity(text),seatleft(text)(int)和date。

此表已填写各种航班计划详细信息。

我想检查用户在预订机票时输入的起始城市和目的地城市是否存在。

代码语言:javascript
复制
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");
                    }
EN

回答 2

Stack Overflow用户

发布于 2018-10-22 13:54:45

是不是要查询的表名为“时间表”而不是“预订”?

此外应该使用参数化查询为SQL查询添加一些安全性。只是将变量连接到查询字符串是不好的做法。

票数 0
EN

Stack Overflow用户

发布于 2018-10-22 15:02:26

将SQL更改为:

代码语言:javascript
复制
String query1 = "SELECT * FROM `booking` WHERE fromcity='"+city[i]+"' AND tocity='"+destination[i]+"';";

我在值和撇号之间包含了间距,因为语句无法编译。我假定city[i]destination[i]TEXTVARCHAR

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档