HiveBrain v1.2.0
Get Started
← Back to all entries
debugsqlModerate

"Invalid object name" error when executing query

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
executingerrorqueryobjectnamewheninvalid

Problem

I connect database with Visual Studio 2017. When I am trying to execute a query then it shows the following error:

The connection string I am using is:

SqlConnection con = new SqlConnection("Data Source=ANUPAM-DESKTOP\ANUPAM;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");


My code:

public void exicuteDatabaseQuery(String query)
    {

        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter(query, con);
        sda.SelectCommand.ExecuteNonQuery();
        con.Close();
        MessageBox.Show("Successfull");

    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        int id = Convert.ToInt32(___Id_.Text);
        int number = Convert.ToInt32(___Number_.Text);
        String InsertQuery = "INSERT INTO Member (id, number) 
        values('"+id+"','"+number+"')";

        exicuteDatabaseQuery(InsertQuery);
    }


Database explorer image:

Solution

I'd guess the problem is your SQL Server login does not have it's "default database" properly set.

This will show you what your "default database" is set to:

SELECT sp.name
    , sp.default_database_name
FROM sys.server_principals sp
WHERE sp.name = SUSER_SNAME();


You can either change the default database of your login, or you can specify the database in the connection string.

This will modify your default database:

ALTER LOGIN  WITH DEFAULT_DATABASE = [testDB];


If you want to specify the database in the connection string, make your connection string:

SqlConnection con = new SqlConnection("Data Source=ANUPAM-DESKTOP\\ANUPAM;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;Initial Catalog=testDB");

Code Snippets

SELECT sp.name
    , sp.default_database_name
FROM sys.server_principals sp
WHERE sp.name = SUSER_SNAME();
ALTER LOGIN <login_name> WITH DEFAULT_DATABASE = [testDB];

Context

StackExchange Database Administrators Q#200288, answer score: 13

Revisions (0)

No revisions yet.