Java mysql查询不起作用

时间:2013-11-06 19:53:11

标签: java mysql sql

我对这些代码行感到困惑和沮丧:

 String updateSQL="UPDATE " + tableName + " set " + secondColumn + "='"+ value2 + "',"+ thirdColumn + "='"+ value3 +"'" + "," + fourthColumn +"='"+ value4 +"'" + "where " + firstColumn + " = "+ checkvalue ;

我让这个查询完美运行!虽然我有另一个查询不完美,但它的风格相同:

  String updateSQL="UPDATE " + tableName + " set "  + secondColumn + "='"+ value2 +"'" + ","+ thirdColumn + "='"+ value3 +"'" + "," + fourthColumn +"='"+ value4 +"'" + "," + fifthColumn +"='"+ value5 +"'" + "where " + firstColumn + " = "+ checkvalue ;

在尝试更新时运行此行代码时我收到错误消息“Where子句中的'PNO3'中的未知列”

虽然我知道我在第一列中有PNO3,并且在第一个查询中执行相同操作时它会找到它吗?有什么帮助吗?

我正在使用此switch语句来确保列指向正确的列。

  switch (tableName) {            
             case "s":  
                 firstColumn = "ID";
              secondColumn = "Namn";
              thirdColumn = "Efternamn";
              fourthColumn = "Adress";
                 break;
             case "p":
                  firstColumn = "PNO";
              secondColumn = "PNAME";
              thirdColumn = "COLOR";
              fourthColumn = "WEIGHT";
              fifthColumn = "CITY";
                 break;
             case "j":
                   firstColumn = "JNO";
              secondColumn = "JNAME";
              thirdColumn = "CITY";           
                 break;
             case "spj":
                  firstColumn = "SNO";
              secondColumn = "PNO";
              thirdColumn = "JNO";
              fourthColumn = "QTY";
                 break;

         }

2 个答案:

答案 0 :(得分:1)

您的第二个查询缺少checkvalue周围的单引号,但它将被视为列名而不是值(假设firstColumn是varchar)。应该是:

String updateSQL="UPDATE " + tableName + " set "  + secondColumn + "='"+ value2 +"'" + ","+ thirdColumn + "='"+ value3 +"'" + "," + fourthColumn +"='"+ value4 +"'" + "," + fifthColumn +"='"+ value5 +"'" + "where " + firstColumn + " = '"+ checkvalue + "'";

注意:您应该使用PreparedStatement而不是字符串连接。这不仅仅是可读性问题,而是安全问题 - 您的代码容易受到SQL注入

答案 1 :(得分:0)

无法确切地说出问题,但我想 * firstColumn是Varchar(),如果是,则将单引号添加到状态值。 要么 *您将错误的列名传递给您的表。

如果您发布错误,那将非常有用。

建议:使用参数化语法,因为它们比你的容易阅读。