mysql select into返回NULL

时间:2016-04-25 21:36:22

标签: mysql

请帮助我理解, 我需要创建用于在db中创建新用户的存储过程。

Scanner sc = new Scanner(System.in);
String playerName;
int uInput;
public static String[] names = {"DESTROYER","SUBMARINE","CRUISER","BATTLESHIP","AIRCRAFT"};
public static int[] shipL = {2, 3, 3, 5, 6 };

public static void shipSetup()
{
  Scanner sc = new Scanner(System.in); 
  String input = " ";
  int valid = 0;
  int index = 0;
  while(index != 4){
    while (valid !=3){
      System.out.println("Place " + names[index] + " ("+ shipL[index]+ " spaces - Format: Coordinate #1, Coordinate #2, Direction)");
      input = sc.nextLine();
      String[] inputArray;
      inputArray = input.split(",");
      //3 values errors
      if(inputArray.length != 3){System.out.println("ERROR:Invalid Direction");continue;}
        try{
          char z = inputArray[2].charAt(0);
          int x = Integer.parseInt(inputArray[0]);
          int y = Integer.parseInt(inputArray[1]);
          //resets loop
          valid = 0;
          //Input direction errors
          if(z != 'V' && z != 'H'){
            System.out.println("ERROR:Invalid Direction - Vertical|V| or Horizontal|H|");
          }
          else{
            ++valid;
          }
          //Input cord errors
          if(x > 9 || x < 0){
            System.out.println("ERROR:Invalid Coordinate - Coordinate must be 1 - 9");
          }
          else{
            ++valid;
          }
          if(y > 9 || y < 0){
            System.out.println("ERROR:Invalid Coordinate - Coordinate must be 1 - 9");
          }
          else{
            ++valid;
          }
        } catch(NumberFormatException e){
          System.out.println("ERROR: Coordinate are numbers dumbASS");
        }
      }
    } 
  }

当我 delimiter // CREATE PROCEDURE add_user (x VARCHAR(25)) BEGIN DECLARE x VARCHAR(25) DEFAULT 'mark'; DECLARE newname VARCHAR(25); DECLARE xid INT; SELECT x, id INTO newname, xid FROM users WHERE x = x; SELECT newname; END; delimiter ; 它告诉我:          call add_user('peter'); 我哪里出错?

1 个答案:

答案 0 :(得分:2)

CREATE PROCEDURE add_user (x VARCHAR(25))
BEGIN
  DECLARE x VARCHAR(25) DEFAULT 'mark';

这实际上会创建名为x两个变量。第一个是函数参数,第二个是局部变量,它位于BEGIN ... END块内。根据MySQL的scoping rules,只有其中一个变量可见,这意味着参数xBEGIN ... END块中隐藏且无法访问。

解决方案只是删除行

  DECLARE x VARCHAR(25) DEFAULT 'mark';

并且,如果您需要指定默认值,请在IF块中执行:

IF x IS NULL THEN
  SET x = 'mark';
END IF;

完整的函数定义应该是

delimiter //    
CREATE PROCEDURE add_user (x VARCHAR(25))
BEGIN
  DECLARE newname VARCHAR(25);
  DECLARE xid INT;

  IF x IS NULL THEN
    SET x = 'mark';
  END IF;

  SELECT x, id INTO newname, xid
    FROM users WHERE x = x;
  SELECT newname;
END;
delimiter ;