简体   繁体   中英

Invalid object name even if it exists

Here is my code:

   InitializeComponent();
   SqlConnection myConnection = new SqlConnection("data source = DESKTOP-77FA1JE;" +
             "user id = DESKTOP-77FA1JE\\Chanloi" +
             "initial catalog = TransactionProcessingSystem;" +
             "integrated security = SSPI");

   myConnection.Open();

    SqlCommand myCommand = new SqlCommand("select * from UserAccounts", myConnection);
   SqlDataReader myReader = myCommand.ExecuteReader();

   BindingSource mySource = new BindingSource();
   mySource.DataSource = myReader;

   dataGridView1.DataSource = mySource;

   myConnection.Close();

I get this error:

System.Data.SqlClient.SqlException: 'Invalid object name 'UserAccounts'.'

Very simple - You do not have a table called UserAccounts in your database. Please try dbo.UserAccounts

In Such a Case What I Usually Do Is Run This Statment

 select name from sys.tables

sys.Tables is a System View That Has info About The Existing Tables In Your Db , This Way You Can Check If The Table Already Exists or U Misspelled It's Name or Existed By Another Name , and Even But an if Condition To Execute Your Logic Only If This Table Exists

Also as Other Have Said it's A Good Practice To Put Column Names Between a [] Brackets , and Call It By Schema Name like dbo.MyTable

try this:

select * from dbo.[UserAccounts]

It's pretty straightforward. It's telling you that there is no UserAccounts table on your database. You can try dbo.UserAccounts , but if it fails, check your database first and also make sure you're connecting to right database.

Hope it helps!

上面的异常表明,通过连接字符串连接的数据库中不存在UserAccounts表

if the table is created do a local refresh cahce from Edit section and then intellisense and then refresh lcoal cache

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