So I am currently learning a little about java and sql, using MySQL. I wrote a function to insert a new row into a table using a prepared statement. I created an array for the values I want to put in so I can loop over them. Since the columns have differing datatypes, I tried using the getMetaData().getColumnTypeName() method to use the appropriate function for the datatype, but it just gives me a null pointer exception.
I tried using the same approach in a regular statement using ResultSet and it worked just fine. Here is my function:
public void insertCustomer() {
try {
ps = connection.prepareStatement("INSERT INTO customers(customerNumber, customerName, contactLastName, contactFirstName," +
" phone, addressLine1, addressLine2, city, state, postalCode, country, " +
" creditLimit) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
String[] columns = {"customerNumber(int)", "customerName(String)", "contactLastName(String)",
"contactFirstName(String)", "phone(String)", "addressLine1(String)", "addressLine2(String)",
"city(String)", "state(String)", "postalCode(String)", "country(String)", "creditLimit(double)"};
String[] values = new String[12];
for(int i = 0; i < columns.length; i++) {
System.out.print("Enter " + columns[i] + ": ");
values[i] = input.nextLine();
/* Gives NullPointerException
if(ps.getMetaData().getColumnTypeName(i + 1).equals("INT"))
ps.setInt(i + 1, Integer.parseInt(values[i]));
if(ps.getMetaData().getColumnTypeName(i + 1).equals("VARCHAR"))
ps.setString(i + 1, values[i]);
if(ps.getMetaData().getColumnTypeName(i + 1).equals("DOUBLE"))
ps.setDouble(i + 1, Double.parseDouble(values[i]));*/
}
ps.setInt(1, Integer.parseInt(values[0]));
ps.setDouble(12, Double.parseDouble(values[11]));
for(int i = 1; i < values.length - 1; i++) {
ps.setString(i + 1, values[i]);
}
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
I commented out the code giving me the exception. They should replace the 5 lines of code below the if statements.
Again, Im really new to SQL and Java so keep that in mind :)