Robert McGuire
Robert McGuire

Reputation: 3

MySQL database not inserting data

I am trying to get this java web application to insert to the database. The error I am getting is noted in the image below.

Problem: when I call insertDB() it works because the id column is counting 1, 2, 3, ... but the rest of the data inside customers36 table is all blank when I pass all the data in. The display() method works but the insert does not and I am running out of things it could be.

Image showing that the data is not getting to the database.

note: selectDB() //works also

Trying to be as specific as I possibly can. The data in the db is all strings with the exception of the id column. That's why I sent all string's to the db.

//Code is for a java bank application.    
package Business;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author DEVGRU
 */
public class Customer
{
    //properties
    private String custId;
    private String custPassword;
    private String custFname;
    private String custLname;
    private String address;
    private String email;
    Connection con = null;

    //Constructors
    public Customer()
    {
        custId = "";
        custPassword = "";
        custFname = "";
        custLname = "";
        address = "";
        email = "";
    }

    public Customer( String id, String pw, String fn, String ln, String add, String em )
    {
        custId = id;
        custPassword = pw;
        custFname = fn;
        custLname = ln;
        address = add;
        email = em;
    }

    //Setters and getters.
    public void setCustId( String id )
    {
        custId = id;
    }

    public String getCustId()
    {
        return custId;
    }

    public void setCustPassword( String pw )
    {
        custPassword = pw;
    }

    public String getCustPassword()
    {
        return custPassword;
    }

    public void setCustFirstName( String fn )
    {
        custFname = fn;
    }

    public String getCustFirstName()
    {
        return custFname;
    }

    public void setCustLastName( String ln )
    {
        custLname = ln;
    }

    public String getCustLastName()
    {
        return custLname;
    }

    public void setAddress( String add )
    {
        address = add;
    }

    public String getAddress()
    {
        return address;
    }

    public void setEmail( String em )
    {
        email = em;
    }

    public String getEmail()
    {
        return email;
    }

    //Db Management and Manipulation methods

    /**
     * @param id@throws ClassNotFoundException
     */
    public void selectDb( String id ) throws ClassNotFoundException
    {
        Class.forName( "com.mysql.jdbc.Driver" );
        try
        {
            //Get the connection and stick it in con.
            con = DriverManager.getConnection( Settings.mysql_connstring, Settings.mysql_user, Settings.mysql_password );
            Statement stmt = con.createStatement();
            String sql;                                             //Single Quotes Arround String Data.Pay Attention.
            sql = "Select * from `JavaChatBankDB`.`Customers` where CustID = '" + id + "'";
            System.out.println( sql );
            ResultSet rs;
            //Execute
            rs = stmt.executeQuery( sql );
            //Process

            while ( rs.next() )
            {
                custId = rs.getString( 1 );
                custPassword = rs.getString( 2 );
                custFname = rs.getString( 3 );
                custLname = rs.getString( 4 );
                address = rs.getString( 5 );
                email = rs.getString( 6 );

            }//End while              
        }
        catch ( SQLException ex )
        {
            System.out.println( "Error somewhere. " + ex );
        }
        finally
        {
            try
            {
                con.close();
            }
            catch ( SQLException ex )
            {
                Logger.getLogger( LoginServlet.class.getName() ).log( Level.SEVERE,
                        null, ex );
            }//End Try/Catch on connection.close() -- sqlexception.
        }//End Finally
    }//End Select Db

    public void insertDB( String id, String pw, String fn, String ln, String add,
            String em ) throws ClassNotFoundException
    {
        Class.forName( "com.mysql.jdbc.Driver" );
        try
        {
            //Get the connection and stick it in con.
            con = DriverManager.getConnection( Settings.mysql_connstring, Settings.mysql_user, Settings.mysql_password );
            Statement stmt = con.createStatement();
            //Single Quotes Arround String DataPay Attention.
            String sql = "INSERT INTO `JavaChatBankDB`.`Customers36` (`CustId`,`CustPassword`, `CustFirstName`, `CustLastName`, `CustAddress`, `CustEmail`)"
                         + "VALUES ('" + custId + "','" + custPassword + "','" + custFname + "','" + custLname + "','" + address + "','" + email + "')";
            System.out.println( sql );
            int answer = stmt.executeUpdate( sql );
            if ( answer >= 1 )
            {
                System.out.println( "Success on Inserting Data into the Database. Go Check!!!" );
            }
            else
            {
                System.out.println( "An error occured while attempting to update database" );
            }

            custId = id;
            custPassword = pw;
            custFname = fn;
            custLname = ln;
            address = add;
            email = em;
        }
        catch ( SQLException ex )
        {
            System.out.println( "Error somewhere. " + ex );
        }
        finally
        {
            try
            {
                con.close();
            }
            catch ( SQLException ex )
            {
                Logger.getLogger( LoginServlet.class.getName() ).log( Level.SEVERE, null, ex );
            }//End Try/Catch on connection.close() -- sqlexception.
        }//End Finally
    }//End Select Db

    public void display()
    {
        System.out.println( "_________Display___________" );
        System.out.println( "                           " );
        System.out.println( "Customer Id: " + custId );
        System.out.println( "Customer Password:" + custPassword );
        System.out.println( "Customer First Name: " + custFname );
        System.out.println( "Custoner Last Name: " + custLname );
        System.out.println( "Customer Address: " + address );
        System.out.println( "Customer Email: " + email );

    }

    public static void main( String[] args ) throws ClassNotFoundException
    {
        //Customer c1 = new Customer("4567","root","mike","baules","afghanistan","[email protected]");

        Customer c2 = new Customer();
        //c2.selectDb("3006");
        c2.insertDB( "3007", "apple", "Steve", "Jobs", "cali", "[email protected]" );
        c2.display();

    }
}//End Class

Upvotes: 0

Views: 175

Answers (2)

Progman
Progman

Reputation: 19546

You are setting the values for your query AFTER you have send it. Well, that's too late, the query is already sent (with default or previous values). So instead of:

String sql = "INSERT INTO `JavaChatBankDB`.`Customers36` (`CustId`,`CustPassword`, `CustFirstName`, `CustLastName`, `CustAddress`, `CustEmail`)"
               + "VALUES ('"+custId+"','"+custPassword+"','"+custFname+"','"+custLname+"','"+address+"','"+email+"')";
int answer = stmt.executeUpdate(sql);
[...]
custId = id;
custPassword = pw;
custFname = fn;
custLname = ln;
address = add;
email = em;

you have to either swap the order or don't use the variables custId, custPassword, etc. at all and use the method parameter values id, pw, etc. directly instead.

Additionally you should use prepared statements for queries with variable input to prevent any SQL injections. Please read https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html on how to use prepared statements with JDBC in java.

Upvotes: 1

Kingkostia
Kingkostia

Reputation: 1

Code should be split in multiple classes ex: DbHelper and Customer. Please be more specific about your question because i only see you inserting 1 customer with id of 3007 type string? Also consider using Long for id or AtomicLong.

Upvotes: 0

Related Questions