Akari
Akari

Reputation: 3

how to solve com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'task4DB.tst' doesn't exist exceptions

I'm a student and I've tried to write this code in order to display the first name of employees which are stored in a database on "mysql" server and I've got these exception although the table exist!! :

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'task4DB.tst' doesn't exist at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723) at com.mysql.jdbc.Connection.execSQL(Connection.java:3283) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1467)

how to solve these problems :( ??

public static void search() throws ClassNotFoundException, SQLException

{    
     Class.forName("com.mysql.jdbc.Driver");

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/task4DB?"
              + "user=root&password=123");

   PreparedStatement st = con.prepareStatement("select * from tst");

    ArrayList<String> fName = new ArrayList<String>();
    ArrayList<String> lName = new ArrayList<String>();
    ArrayList<Integer> ids = new ArrayList<Integer>();


    ResultSet RS=st.executeQuery("select * from tst ");

      loop1:
    for(String s : fName )

    {

          while (RS.next()) {
fName.add(RS.getString("fName"));


    }

      for(int i=0;i<fName.size();i++ )

      {
          System.out.println(fName.get(i));

      }

}

Upvotes: 0

Views: 5550

Answers (2)

sidgate
sidgate

Reputation: 15244

it should be con.prepareStatement("THE_SQL_QUERY")

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500645

Well createStatement doesn't return a PreparedStatment - it returns a Statement. You need to pass the SQL to the prepareStatement method instead:

PreparedStatement st = con.prepareStatement("select * from tst");

Then:

ResultSet rs = st.executeQuery();

While you can still call the overload of executeQuery which takes SQL, you generally shouldn't. (I think it was probably a mistake to make PreparedStatement extend Statement.)

Note that you should also close the connection, statement, and result set in finally blocks. Also, I've renamed your RS variable to follow Java naming conventions somewhat, although I'd probably just call it results or something similar.

Additionally, your loop is broken - fName is empty, so there's no point in looping over it. You probably want:

while (rs.next()) {
    fName.add(rs.getString("fName"));
}

Upvotes: 4

Related Questions