我正在做一个 Java WebService,它执行一些 SQL 查询。
SELECT FROM a table 方法工作正常。 但 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()); }
}
提前致谢。
最佳答案
插入时,交换
statement.executeQuery
与
statement.executeUpdate
关于Java 和 MySQL,SELECT 有效;插入不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22375388/