2

I am trying to create the table through java string but it is displaying error as table doesn't exist but when I run the same query directly on workbench it runs fine. Below is my code

String url = "jdbc:mysql://localhost:3306/" ;
String dbname = "tweetmap";
String username = "root";
String password = "root";
try
{ 
    // SQL Driver needed for connecting to Database
    Class.forName("com.mysql.jdbc.Driver");
    c = DriverManager.getConnection(url+dbname,username,password);
    c.setAutoCommit(true);
    stmt = c.createStatement();

    //Creating the Database if not Already Present
    String sql = "CREATE TABLE if not exists senti "
            + "( latitude double NULL, "
            + "longitude double NULL, "
            +  "Sentiment TEXT  NULL) ";
    stmt.executeUpdate(sql);

    if(sentiment != null){

        stmt1 = c.createStatement();    
        stmt1.executeUpdate("INSERT INTO `senti`(latitude,longitude,Sentiment) VALUE ('"+lati+"','"+longi+"','"+sentiment+"')");
        }
    }
catch(Exception e){
     e.printStackTrace();
}
10
  • Are you getting any exception? Commented May 4, 2015 at 4:53
  • I think it's bcoz u haven't specify primary key for the table & remove IF NOT EXISTS clause from the query. Try the same. Commented May 4, 2015 at 4:56
  • 1
    Please refer below link. May that help you. tutorialspoint.com/jdbc/jdbc-create-tables.htm Commented May 4, 2015 at 4:57
  • I have written according to this tutorial only, the thing is that when I run my query directly on workbench it works fine and there is no atrribute in my table that requires primary key Commented May 4, 2015 at 5:03
  • Checkout this stackoverflow.com/questions/19016363/… Commented May 4, 2015 at 5:04

2 Answers 2

5

this is the problem stmt.executeUpdate(sql);

instead of executeUpdate use execute(String SQL) method.

execute(String SQL) is used for DDL/DML statement while executeUpdate(String SQL) is used only for DML operation

Sign up to request clarification or add additional context in comments.

Comments

0

Best way to execute any query in JDBC is using execute() method. This method can be used for any kind of query. I hope below link will help you to understand more.

http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#execute(java.lang.String)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.