Search code examples
c#sqlconnection

Invalid Object Name in ExecuteNonQuery


I'm currently trying to develop an application that allows you to track your spending as part of my class. However I run into the error "Invalid object name 'dbo.AccTransactions"

My Windows Form Code:

    string command = "Insert INTO dbo.AccTransactions (id, transact_id, payee, dateof, amount, category)"
                            + "Values (@id, @transact_id, @payee, @dateof, @amount, @category)";
        SqlCommand cmd = new SqlCommand(command, con);
        cmd.Parameters.AddWithValue("@id", 1);
        cmd.Parameters.AddWithValue("@transact_id", 2);
        cmd.Parameters.AddWithValue("@payee", payeeTextBox.Text);
        cmd.Parameters.AddWithValue("@dateof", DateTime.Today);
        cmd.Parameters.AddWithValue("@amount", Convert.ToDecimal(amountTextBox.Text));
        cmd.Parameters.AddWithValue("@category", categoryTextBox.Text);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

My Connection String:

     SqlConnection con = new SqlConnection(@"Data Source=IVY\SQLEXPRESS;Initial Catalog=BudgetTracker;Integrated Security=SSPI;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");

My database has the table "dbo.AccTransactions" and it performs perfectly in SSMS.

Any assistance would be great!


Solution

  • I guess you are missing database name in the connection string.

    SqlConnection con = new SqlConnection(@"Data Source=IVY\SQLEXPRESS;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
    

    try it by putting the name of your database in the following string.

     SqlConnection con = new SqlConnection(@"Data Source=IVY\SQLEXPRESS; Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");