Java和MySQL,SELECT工作; INSERT没有

时间:2014-03-13 10:17:25

标签: java mysql select insert

我正在做一个Java WebService,它会打开一些SQL查询。

SELECT FROM表方法正常工作。 但INSERT INTO声明没有;它实际上并没有更新数据库的表。我猜是为什么。

SELECT FROM方法:

@WebMethod(operationName = "retrievePlayer")
public String retrievePlayer(@WebParam(name = "user") String user, @WebParam(name = "password") String password)
    {

    String customerInfo = "";

    try
      {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");

      PreparedStatement statement
        =  con.prepareStatement("select user, password, level from mytable where user=\"" + user + "\";");
       ResultSet result = statement.executeQuery();

       while(result.next())
          {
          customerInfo = customerInfo
                     + result.getString("user")
                     + "&" + result.getString("password")
                     + "&"+result.getString("level");
          }
       }
       catch(Exception exc){ System.out.println(exc.getMessage()); }        

       return customerInfo;
       }

INSERT方法,不起作用:

@WebMethod(operationName = "createPlayer")
public void createPlayer(@WebParam(name = "user") String user, @WebParam(name = "password") String password)
    {
    try
      {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");

      PreparedStatement statement
            =  con.prepareStatement("insert into mytable ('user', 'password', 'level') values ('" + user + "','" + password + "','0,1');");
      statement.executeQuery();*/

      }
    catch(Exception exc){ System.out.println(exc.getMessage()); }
    }

提前致谢。

4 个答案:

答案 0 :(得分:0)

插入时,交换

statement.executeQuery

statement.executeUpdate

答案 1 :(得分:0)

使用

<强>的Statement.executeUpdate();

用于插入

使用

String sql = "INSERT INTO mytable (user, password, level)" +
        "VALUES (?, ?, ?)";


PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "user");
preparedStatement.setString(2, "password");
preparedStatement.setString(3, "0,1");
preparedStatement.executeUpdate(); 

答案 2 :(得分:0)

你应该使用这段代码:

public void addUser(User user)
    {
        try
        {   
Query=insert into mytable (user, password, level) values (?,?,?)");
PreparedStatement Statement = conn.prepareStatement(Query);
Statement.setString(1, user.getuser());
Statement.setString(2, user.getpassword());
Statement.setString(3, user.getlevel());
Statement.executeUpdate();              
}
catch(Exception e)
{
System.out.println(e);
}
}

答案 3 :(得分:0)

您必须将查询更改为statement.executeupdate