2013-01-14 54 views
1

我剛開始學習MySQL和JDBC。MySQLSyntaxErrorException

我使用phpmyadmin創建了一個名爲testdb的表。表格只有2列稱爲第一個和最後一個。當我嘗試從我的java類連接數據庫時,出現MySQLSyntaxError。但我無法弄清楚。

這裏是我的類:

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 

public class Main { 

    public static void main(String[] args) throws ClassNotFoundException, SQLException { 
     String url = "jdbc:mysql://localhost:3306/testdb"; 

     //Accessing driver from the JAR file. 
     Class.forName("com.mysql.jdbc.Driver"); 

     //Creating a variable for the connection "con" 
     Connection con = DriverManager.getConnection(url,"root","password"); 

     //Here is the query 
     PreparedStatement statement = con.prepareStatement("select * from name"); 

     //Execute query 
     ResultSet result = statement.executeQuery(); 

     while(result.next()) { 
      System.out.println(result.getString(1) + " " + result.getString(2)); 
     } 


    } 

} 

這裏是例外:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'testdb.name' doesn't exist 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) 
    at com.mysql.jdbc.Util.getInstance(Util.java:386) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028) 
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490) 
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651) 
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734) 
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155) 
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322) 
    at Main.main(Main.java:22) 

謝謝您的幫助

回答

2
MySQLSyntaxErrorException: Table 'testdb.name' doesn't exist 

錯誤是相當多的描述。在testdb模式中沒有名稱爲「name」的表。

我使用phpmyadmin創建了一個名爲testdb的表。

如果你已經創建了表testdb那麼它應該是select * from testdb。不是嗎?

+0

謝謝你,我錯過了:) – skynyrd

+0

@AnılSelimSürmeli:不客氣。很高興幫助。祝你好運。 – kosa

2

你已經創建了一個名爲表TESTDB 因此您的查詢應該是

select * from testdb 

select * from name

你應該檢查你的蹤跡。

相關問題