我正在制作一个基本的java服务器(客户端将在稍后出现),它将访问我的MySQL数据库。它应该只是检查输入的用户名是否存在。如果确实如此,如果没有创建记录。在玩了一堆不同的东西试图让它工作,但我遇到(rs.next),当我使用它时,我得到错误找不到它的符号。 这是我的代码。
public void run()
{
final String queryCheck = "SELECT * from account WHERE username = ?";
try
{
ObjectInputStream FromClient = new ObjectInputStream(
client.getInputStream());
ObjectOutputStream ToClient = new ObjectOutputStream(
client.getOutputStream());
InetAddress inetAddress = client.getInetAddress();
String host = "jdbc:mysql://localhost/midterm";
String user = "scott";
String pass = "tiger";
String database = "midterm";
Connection conn = DriverManager.getConnection(host,user,pass);
PreparedStatement stmt = conn.prepareStatement(queryCheck);
System.out.print("Connected to database\n");
System.out.println("Connect to Client " + clientID + " at " + inetAddress.getHostName() + " " + inetAddress.getHostAddress());
// create data input and out streams
while(true)
{
Object objReceived = FromClient.readObject();
Object objReceived2 = FromClient.readObject();
String username = objReceived.toString();
String userpass = objReceived2.toString();
System.out.print("\nInput received: " + "\nUsername: " + username + " Password: " + userpass);
try
{
stmt.setString(1, username);
//stmt.setString(2, userpass);
ResultSet rs = stmt.executeQuery();
boolean recordAdded = false;
if (!rs.next())
{
stmt.addBatch();
stmt.executeBatch();
recordAdded = true;
}
if (recordAdded)
{
String txt = ("Account Created!!");
ToClient.writeObject(txt);
System.out.println("Account has been Created!");
recordAdded = false;
}else
{
String txt = ("Username already exists!");
ToClient.writeObject(txt);
System.out.println("\nAccount already exists!");
}
}
catch (Exception ex)
{
}
//conn.close();
}
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
坦率地说,我不确定我是否走在正确的轨道上。我在这里看到过有关同一事情的其他帖子,但他们的代码与next()一起使用,而我的代码则没有。任何反馈都表示赞赏。
答案 0 :(得分:1)
下面
while (!rs.next)
你说的是 rs
没有下一个元素 ......
要迭代ResultSet
,您必须删除!
,这样您就可以:
while (rs.next) // you say, while there are more elements, loop...
{
stmt.addBatch();
stmt.executeBatch();
recordAdded = true;
}
答案 1 :(得分:1)
while (!rs.next) // I have also tried stmt.next
{
stmt.addBatch();
stmt.executeBatch();
recordAdded = true;
}
将上述代码替换为:
if(rs.next())
{
stmt.addBatch();
stmt.executeBatch();
recordAdded = true;
}