简体   繁体   中英

java.sql.SQLException [Microsoft] [ODBC SQL Server Driver] [SQL Server] Invalid object name 'table name'

When I connect Java to Mssql using JDBC ODBC driver

try 
{
    ps=conn.prepareStatement("UPDATE products SET stock=? WHERE id=?");

    ps.setInt(1, prods.getStock());
    ps.setInt(2, prods.getId());

    int b = ps.executeUpdate();

    if(b!=0)
    {
        System.out.println("success");
    }
    else
    {
        System.out.println("Fail");
    } 
}
catch(SQLException e)
{
    System.out.println(e);
}

This catch block rises this exception

java.sql.SQLException [Microsoft] [ODBC SQL Server Driver]
  [SQL Server] Invalid object name 'products'

I am working on this part from last 2 days. How I will solve this exception?

This error message is thrown when the table can't be found. That can have several reasons:

  • you are connecting to a different DB
  • the table was deleted
  • the table is in another DB schema
  • your user does not have read permissions on that table any more

I'd imagine that your connection string has no default database - you are probably connecting to 'master' in which case the above won't work

You can test this by qualifying your query with the database and schema name:

eg

ps=conn.prepareStatement("UPDATE [YourDatabaseName].[schema].products SET stock=? WHERE id=?"); 

put your values in where needed (standard default schema is 'dbo' eg. ProductsDatabase.dbo.products)

If this works then your connection string is incorrect

Normally this exception is thrown if the table does not exist, or that there is an error with the connection string. Maybe not connecting to the correct database?

I ran into similar issue. Cause of the issue in my case was the user running the report has the DEFAULT_DATABASE pointing to the master database, after changing it to the right database it was able to locate the object.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM