-2

I would like to store a value in database if it is not present if not I would like to insert but I was facing a problem:

java.lang.NullPointerException..

String read = "flavour"; 

public static void dataStore(String read) {

    try {

        Connection connect = null;
        ResultSet rs = null;
        PreparedStatement st = null;

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        // Setup the connection with the DB
        connect = DriverManager.getConnection("jdbc:sqlserver://WMDENTW1\\SQLEXPRESS:1433;" + "database=FullTextDB;"
                + "user=root;" + "password=root123");
        String key = "IF EXISTS (SELECT * FROM QueryStrings WHERE Query_String= '"+read+"') UPDATE QueryStrings SET Query_Count=Query_Count + 1 WHERE Query_String ='"+read+"' ELSE INSERT INTO QueryStrings VALUES ('"+read+"', 1)";

        st.executeQuery(key);
        System.out.println("data commited");
        connect.commit(); 

    } catch(Exception e) {
        System.out.println(e);
    }
}
dur
  • 15,689
  • 25
  • 79
  • 125
gupta k
  • 23
  • 1
  • 9

1 Answers1

1

The PreparedStatement st is null when you call st.executeQuery(). You need to create a statement, like st = conn.createPreparedStatement(key);

Alternatively, you can create a simple statement:

Statement st = conn.createStatement();
st.executeQyery(key);
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49