NullPointerException on statement.executeUpdate() [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I created a website with JSP and Java, it simply displays a form (it's a user registration form) where the user can fill it, then I want it to be stored in a database.
I installed Eclipse, Tomcat (to host on localhost 8080) and Wampserver (to have phpmyadmin and my SQL database).
I've tried to create an ORM (Object-relational mapping), so when the client submits the form, it sends the datas to my ORM, my ORM then stores the datas in my database.
The issue is, when the user submit submits the form, my table is created (I can see it on phpmyAdmin), so it's very good. But it crashes on my website and creates an error
HTTP500, java.lang.NullPointerException.
It says the problem is on
com.jweb.bdd.Orm.Perform(Orm.java:139)
Here is my code in my CreateClient.java file, this java file handles the servlet of my registration form:
public class CreationClient extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
[...]
String lastName= request.getParameter( CHAMP_LASTNAME);
String Name= request.getParameter( CHAMP_NAME);
String mailAdress = request.getParameter( CHAMP_MAILADRESS);
String phoneNumber= request.getParameter( CHAMP_PHONENUMBER);
String login= request.getParameter( CHAMP_LOGIN);
[...]
Orm orm = new Orm();
String[] field = {"login", "firstName", "lastName", "mailAdress", "adress", "phoneNumber", "password"};
String[] values = {login, firstName, lastName, mailAdress, adress, phoneNumber, password};
orm.Insert("client", field);
orm.Values(values);
orm.Perform();
orm.CloseConnection();
[...]
}
}
Here is my Perfom() function in my ORM class:
public void Perform(){
ResultSet rst = null;
if (select != null){
if (from != null && where != null){
try {
rst = statement.executeQuery(select + from + where);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
int i = 0;
while (rst.next()){
res[i] = rst.getString(0) + ":" + rst.getString(1)+ ":" + rst.getString(3) + ":" + rst.getString(4) +":" + rst.getString(5) + ":" + rst.getString(6)+ ":" + rst.getString(7) + ";";
i++;
}
} catch (SQLException e){
e.printStackTrace();
}
}
}
else if (insert != null){
if (values != null){
try {
// statement = connexion.creatStatemnt();
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
try {
rst.close();
} catch (SQLException ignore){
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
}
And the error on the line 139 is the int res = statement.executeUpdate(insert + values); :
else if (insert != null){
if (values != null){
try {
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
Do you have any idea how to fix this issue of NullPointer?
Thanks.

You need to initialize your statement object, In your code you used statement.executeQuery() but not statement = connection.createStatement() initialize statement object.

Related

JavaEE does not throw SQLException when primary key is duplicated

I am studying on a Java Web Application with JavaEE (not SPRING). But I have ran into a problem that my application doesn't throw SQLException when a row is inserted into table with duplicated primary key.
In details, I have a DAO class AccountInfoDAO.java with a createNewAccount method:
public boolean createNewAccount(String username, String password,
String fullName, boolean role)
throws NamingException, SQLException {
boolean result = false;
Connection con = null;
PreparedStatement stmt = null;
int iCount = 0;
try {
con = DBHelpers.makeConnection();
if (con != null) {
String queryStr = "INSERT INTO "
+ "accountInfo(username, password, lastname, isAdmin) "
+ "VALUES(?, ?, ?, ?)";
stmt = con.prepareStatement(queryStr);
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setNString(3, fullName);
stmt.setBoolean(4, role);
iCount = stmt.executeUpdate();
if (iCount > 0) {
result = true;
}
} // EndIf Connected
} finally {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
return result;
}
}
And my functional Servlet CreateNewAccountServlet.java with the processRequest method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("txtUsername");
String password = request.getParameter("txtPassword");
String confirm = request.getParameter("txtConfirm");
String fullname = request.getParameter("txtFullname");
String url = ERROR_PAGE;
AccountInfoCreateError errors = new AccountInfoCreateError();
boolean foundErr = false;
try {
// 1. Check valid user input
if (username.trim().length() < 6 || username.trim().length() > 30) {
foundErr = true;
errors.setUsernameLengthErr("Username requires input from 6 to 30 characters!");
}
if (password.trim().length() < 6 || username.trim().length() > 20) {
foundErr = true;
errors.setPasswordLengthErr("Password requires input from 6 to 20 characters!");
} else if (!password.trim().equals(confirm.trim())) {
foundErr = true;
errors.setConfirmNotMatch("Confirm mus be matched with password!");
}
if (fullname.trim().length() < 2 || fullname.trim().length() > 50) {
foundErr = true;
errors.setFullNameLengthErr("Full name requires input from 2 to 50 characters!");
}
if (foundErr) {
request.setAttribute("CREATE_ERROR", errors);
} else {
// 2. Call DAO
AccountInfoDAO dao = new AccountInfoDAO();
boolean result = dao.createNewAccount(username, password, fullname, false);
if (result) {
url = LOGIN_PAGE;
}
}
} catch (SQLException ex) {
String errMsg = ex.getMessage();
log("CreateNewAccountServlet SQL: " + errMsg);
if (errMsg.contains("Duplicate")) {
errors.setUsernameIsExisted(username + " is existed");
request.setAttribute("CREATE_ERROR", errors);
}
} catch (NamingException ex) {
log("CreateNewAccountServlet Naming: " + ex.getMessage());
}
finally {
RequestDispatcher rd = request.getRequestDispatcher(url);
rd.forward(request, response);
out.close();
}
}
When I run my application, everything works well. A normal new account can be created and inserted into database successfully. But when I try to insert an account with a duplicated username (which is my primary key in the table), it doesn't throw SQLException, which is expected to happen. And my TomCat server does not write log, of course.
All of my friends have done this with the exception thrown.
I have tried to re-install my MS SQL Server, try to use different JDBC driver but the result is the same.
I am using JDK 8, NetBeans 8.2 RC, Apache Tomcat 8.0, MS SQL Server 2012 to implement this application.
Hope you can help me to fix this problem!
------- Update
My table design in MS SQL Server
I have found out the solution. I have to put the return result; line out of finally block and my application works well! Thanks for your help!

ResultSet only returns one row when more exist in the database

I created a java class called Executar_Query_Bd_Multiplos_Resultados in this class as the parameter for the Conectar method 2 values (int Integer1, int Integer2) of integer type.
These values are received by the query:
"SELECT DS_ESTRATEGY, STRID_ID" +
"FROM TB_BKOFFICE_ESTRATEGY" +
"WHERE IN_STRATEGY_ID IN (" + Istrategy1 + "," + Istrategy2 + ")";
The result of the above query is stored in the variable ls_command.
In the Executar_Query_Bd_Multiplos_Resultados_Test class I make the method call (Connect) and step 2 parameters (179, 319) and command to print on the screen the variable of type String codEstrategies.
But Eclipse only displays 1 result on the console. The query should bring 2 results and not 1. Here is the code for the Java classes and the result of the query executed in Oracle SQL Developer.
public class Executar_Query_Bd_Multiplos_Resultados_Test {
#Before
public void setUp() throws Exception {
Executar_Query_Bd_Multiplos_Resultados qr_2 = new Executar_Query_Bd_Multiplos_Resultados();
String codEstrategias = qr_2.Conectar(179, 319);
System.out.println("Estratégias: " + codEstrategias);
}
#After
public void tearDown() throws Exception {
}
#Test
public void test() {
}
}
public class Executar_Query_Bd_Multiplos_Resultados {
//Variáveis de BD
Connection conOracle = null;
Statement stmtOracle = null;
ResultSet rsetOracle = null;
public String Conectar(int Id_Estrategia1, int Id_Estrategia2) {
String retorno = "#;-1;#";
Boolean lb_continuar = true;
//StringBuilder ls_comando = new StringBuilder();
String ls_comando = new String();
try {
System.out.println("Conectando ao banco de dados Oracle...");
String url = "";
try {
//conectando aos bancos de dados
Class.forName("oracle.jdbc.driver.OracleDriver");
url = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
DriverManager.setLoginTimeout(10);
conOracle = (Connection) DriverManager.getConnection(url, "bkofficeadm", "bkofficeadmdesenv01");
} catch (SQLException e) {
System.out.println("falha SQL >> " + e.getMessage());
} catch (Exception e) {
//System.out.println("falha geral >> " + e.getMessage());
e.printStackTrace();
lb_continuar = false;
}
//String teste = "'BKO - Rep Conectividade'";
if (lb_continuar) {
System.err.println("Preparando comando...");
System.out.println("");
ls_comando = "SELECT DS_ESTRATEGIA, ID_ESTRATEGIA"+
" FROM TB_BKOFFICE_ESTRATEGIA"+
" WHERE ID_ESTRATEGIA IN (" + Id_Estrategia1 + ", " + Id_Estrategia2 + ")";
System.out.println(ls_comando);
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
rsetOracle = stmtOracle.executeQuery(ls_comando.replaceAll("\n", " ").trim());
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
rsetOracle.close();
stmtOracle.close();
/*
Para comandos de Insert, Delete, ou Update
--------------------------------------------------------
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
stmtOracle.execute(variavel_comando.toString());
conOracle.commit();
stmtOracle.close();
*/
}
} catch (Exception ex) {
System.out.println("Erro - " + ex.getMessage());
} finally {
try {
if (rsetOracle != null) {
rsetOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar rset - " + e.getMessage());
}
try {
if (stmtOracle != null) {
stmtOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar stmt - " + e.getMessage());
}
try {
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar con - " + e.getMessage());
}
}
return retorno;
}
}
Output from SQL Devleoper query:
Output from Eclipse console:
You're doing this
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
This runs once
Consider while instead:
List<String> retornos = new ArrayList<>();
while(rsetOracle.next()) {
retornos.add(rsetOracle.getString(1));
}
This will run until you're out of rows.
If something like this happens in the future, you'll want to modify your query to select count(*) ... and verify you get the same result in both the database workbench and your javacode. Then you'll at least know you've got the right query, and it's your presentation that's failing.
Note:
I understand this question is indeed a duplicate of other questions. However, those are difficult to search. I would propose this be a canonical answer.

Can not insert user into database in JSON Java Restful

I'm facing the problem about insert user in database. Im using Restful and JDBC to parse data to android, I have two classes to perform insert user following as:
Register.java
#Path("/register")
public class Register {
#GET
#Path("/doregister")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("name") String name, #QueryParam("username") String uname, #QueryParam("password") String pwd){
String response = "";
int retCode = registerUser(name, uname, pwd);
if(retCode == 0){
response = Utitlity.constructJSON("register",true);
}else if(retCode == 1){
response = Utitlity.constructJSON("register",false, "You are already registered");
}else if(retCode == 2){
response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
}else if(retCode == 3){
response = Utitlity.constructJSON("register",false, "Error occured");
}
return response;
}
private int registerUser(String name, String uname, String pwd){
System.out.println("Inside check registerUser method() ");
int result = 3;
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
try {
if(DBConnection.insertUser(name, uname, pwd)){
System.out.println("RegisterUSer if");
result = 0;
}
} catch(SQLException sqle){
System.out.println("RegisterUSer catch sqle");
//When Primary key violation occurs that means user is already registered
if(sqle.getErrorCode() == 1062){
result = 1;
}
else if(sqle.getErrorCode() == 1064){
System.out.println(sqle.getErrorCode());
result = 2;
}
}
catch (Exception e) {
System.out.println("Inside checkCredentials catch e ");
result = 3;
}
}else{
System.out.println("Inside checkCredentials else");
result = 3;
}
return result;
}
}
DBConnect.java
public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception {
boolean insertStatus = false;
Connection dbConn = null;
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "INSERT into ACCOUNT(name, username, password) values('"+name+ "',"+"'"
+ uname + "','" + pwd + "')";
//System.out.println(query);
int records = stmt.executeUpdate(query);
//System.out.println(records);
//When record is successfully inserted
if (records > 0) {
insertStatus = true;
}
} catch (SQLException sqle) {
//sqle.printStackTrace();
throw sqle;
} catch (Exception e) {
//e.printStackTrace();
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return insertStatus;
}
My table ACCOUNT:
When I debugged on Eclipse, I see the result return is fine, but If I use Advanced rest client tool to get data, it happened an exception:
URL Json:
http://localhost:9999/webserver/register/doregister?name=tester&username=tester#gmail.com&password=test12345
status of result response:
{
"tag": "register",
"status": false,
"error_msg": "Error occured"
}
I have found and tried a lot of ways but not found the cause
How to fix the problem and insert user into database? Thank so much !

indexof string matching from data base and runtime text

I want to make website blocker in my web browser, so I made a database which contain the names of website. Now I want to check the string from database with indexOf method, but it is giving me an error while I am trying to check. Please tell me where my mistake is. Rest of the code is correct and working only database part is not working.
public void loadURL(final String url) {
try {
Connection myconnection;
myconnection = DriverManager.getConnection("jdbc:mysql://localhost/bookmarks", "roo t", "");
try {
String q = "select * from block where url=?";
PreparedStatement mysat = myconnection.prepareStatement(q);
ResultSet myresult = mysat.executeQuery();
int index1;
while (myresult.next()) {
String s2 = myresult.setString("url");
String s1 = txtURL.getText();
index1 = s1.indexOf(s2);
}
if (index1 == -1) {
JOptionPane.showMessageDialog(rootPane, "You Cannot access this website", "Error", JOptionPane.ERROR_MESSAGE);
} else {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
myconnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if you use PreparedStatement you have to set a
value for each ? marker:
String q="select * from block where url=?";
PreparedStatement mysat=myconnection.prepareStatement(q);
mysat.setString(1,"www.google.com");
without you have an invalid sql syntax.

Allowing column name to be specified makes it a potential SQL injection risk

I have these two methods where I was told that "the fact you allow the column name to be specified is (an SQL) injection risk". What does even mean? To be specified by whom? And how can I fix it?
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
bottomLabel.setText(textForLabel());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
PreparedStatement prepStmt = null;
try {
connection = TableWithBottomLine.getConnection();
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
String updateString = "update finance.fin " + "set ? = ? " + "where ID = ? "+ ";";
prepStmt = connection.prepareStatement(updateString);
prepStmt.setString(1, stulpPav);
prepStmt.setString(2, duom);
prepStmt.setString(3, studId);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (prepStmt != null)
prepStmt.close();
System.out.println("Data was imported to database");
}
}
}
What does even mean? :)
It means, that if the String was changed, you could put in SQL code to do something different, like updating a password, or garnting access to the systems.
To be specified by whom?
Any code which can access the column name, this is only a problem if the user has access to this field.
And how can I fix it?
Check that there really is no way for the user to specify this column name, and ignore the message

Categories