user2801881
user2801881

Reputation: 73

Can anyone see why this SQL insert will not work? (Exception to String and Date to String Inserted) - JDBC

Im trying to basically make a log of errors generated from a Java program and save them in an SQL table with 2 colums( Error and Date )

Try and catch sends the error to the method which should hopefully insert into database but its failing somewhere. Im new enough to Java so im not sure how to debug it properly or get more details on wahts going wrong and where

Heres the method.

public void createErrorLog(Exception error) throws SQLException{

        // Error as String
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        error.printStackTrace(pw);
        sw.toString(); // stack trace as a string
        String errorOne = sw.toString();
        System.out.println(errorOne);

        // Date
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();
        String dateString = dateFormat.format(date);




        Connection conn = null;
        try {       
            conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
            System.out.println("Connected to database.");       

            String insertSaleProperty = "INSERT INTO ErrorLogs"
                    + "(Error, "
                    + "Time, "                  
                    + "(?,?)";
            PreparedStatement preparedStatement = conn.prepareStatement(insertSaleProperty);
            preparedStatement.setString(1, errorOne);
            preparedStatement.setString(2, dateString);
            // execute insert SQL statement
            preparedStatement.executeUpdate();





        } catch (SQLException e) {
            System.err.println("Cannot write to database.");


        } finally {

        if(conn != null){
            conn.close();

          }

        }




    }   

Upvotes: 0

Views: 71

Answers (2)

Bhanu Kaushik
Bhanu Kaushik

Reputation: 864

Try the following.

String insertSaleProperty = "INSERT INTO ErrorLogs"
                           + "(Error,Time) values "                  
                           + "(?,?)";

Upvotes: 4

Bill the Lizard
Bill the Lizard

Reputation: 405765

String insertSaleProperty = "INSERT INTO ErrorLogs"
                + "(Error, "
                + "Time, "                  
                + "(?,?)";

Should probably be:

String insertSaleProperty = "INSERT INTO ErrorLogs "
                + "(Error, Time) "                  
                + "VALUES (?,?)";

Upvotes: 3

Related Questions