gpt4 book ai didi

Java向MySQL插入值并从MySQL返回值

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

我正在创建一个员工登录验证类,我可以将他们的信息插入到 mysql 数据库中,然后为了进行验证,我尝试仅选择该行的密码。这是我的代码:

     import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;


public class Employee
{

private PreparedStatement statement;
private Connection con;
private String pass;
public Employee()
{

}
public Employee(String firstName, String lastName, String userID, String userPassword, String role )
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
statement = con.prepareStatement("Insert into employee(firstName, lastName, userID, " +
"password, role)values(?, ?, ?, ?, ?)");

statement.setString(1, firstName);
statement.setString(2, lastName);
statement.setString(3, userID);
statement.setString(4, userPassword);
statement.setString(5, role);
statement.executeUpdate();
con.close();
}
catch(Exception e)
{

}
}
public void setPassword(String userID)
{
try
{
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
while(rs.next()){
pass = rs.getString(4);
}
}
catch(Exception e)
{
System.out.print(e);
}
}
public String getPassword()
{
return pass;
}


}
and here is my main

public class TestMain
{
public static void main(String argsp[])
{
Employee emp = new Employee();
emp.setPassword("ecka12");
}
}

我遇到了空指针异常,我不知道为什么。

最佳答案

您正在使用以下方式创建对象:-

   Employee emp = new Employee();

在 0-arg 构造函数中,您尚未初始化连接

public Employee() {

}

因此,当您在 setPassword() 方法中使用 con 时,您将得到 NullPointerException : -

    // con is not initialized
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);

要纠正此问题,您需要将以下代码移至 0-arg 构造函数。并在您的其他构造函数中: - 添加 this() 作为您的第一个声明..

public Employee() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","");
} catch (Exception e) {
e.printStackTrace();
}
}



public Employee(String firstName, String lastName) {
this(); // Initialize con..

try {
// You don't need to initialize your con here again..
// Your remaining code..
}
}

关于Java向MySQL插入值并从MySQL返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12746650/

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