gpt4 book ai didi

java - 通过java服务器/客户端将记录添加到MySQL数据库

转载 作者:行者123 更新时间:2023-11-29 07:40:14 25 4
gpt4 key购买 nike

我正在制作一个基本的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() 一起使用,而我的则不能。如有任何反馈,我们将不胜感激。

最佳答案

            while (!rs.next)  // I have also tried stmt.next
{
stmt.addBatch();
stmt.executeBatch();
recordAdded = true;
}

将上面的代码替换为:

            if(rs.next())
{
stmt.addBatch();
stmt.executeBatch();
recordAdded = true;
}

关于java - 通过java服务器/客户端将记录添加到MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29299915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com