尝试将记录插入数据库时,我一直收到空指针异常。我正在进入网络应用程序类,所以我这是我第一次在eclipse中处理数据库。我相信这一行初始化了我的连接变量:
this.connection = DriverManager.getConnection(url, uname, pwd);
...但它仍然说连接为空。它所指的行是:
PreparedStatement ps = connection.prepareStatement(query);
package dbHelpers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import package1.Customer;
public class AddCustomerQuery {
public Connection connection;
public AddCustomerQuery(String dbName, String uname, String pwd){
String url = "jdbc:mysql://localhost:3306/" + dbName;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.connection = DriverManager.getConnection(url, uname, pwd);
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addCustomer(Customer customer){
String query = "insert into customer (firstName, lastName, emailAddress, password, gender, phoneNumber, street, city, state, zip) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, customer.getFirstName());
ps.setString(2, customer.getLastName());
ps.setString(3, customer.getEmailAddress());
ps.setString(4, customer.getPassword());
ps.setString(5, customer.getGender());
ps.setString(6, customer.getPhoneNumber());
ps.setString(7, customer.getStreet());
ps.setString(8, customer.getCity());
ps.setString(9, customer.getState());
ps.setString(10, customer.getZip());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
首先检查你的mysql daatbase服务器用户名,密码,数据库名称等。,。因为默认情况下mysql服务器端口号是3306,可能是在安装时你更改了服务器的端口号。