通过java服务器/客户端将记录添加到MySQL数据库
我正在制作一个基本的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(),而我的代码不能。任何反馈都将不胜感激
# 1 楼答案
这里
你说的是,而
rs
没有下一个元素若要在
ResultSet
上迭代,必须删除!
,这样您将有:# 2 楼答案
将上述代码替换为: