Due
Due

Reputation: 21

SQL Server : not able to insert into table?

I am not sure this an syntax error or a problem with my IDE (Visual Studio), but I can't seem to insert into the table I have added to my project.

private void create_user_username_box_Leave(object sender, EventArgs e)
{
    // Add user/password to database when when someone leaves the area. 
    using (DbConnection connection = new SqlConnection(@"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
    {
        connection.Open();

        using (DbCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id, password) VALUES (@id, @pw);"))
        {
            command.Parameters.Add(new SqlParameter("@id", create_user_username_textbox.Text));
            command.Parameters.Add(new SqlParameter("@pw", create_user_password_textbox.Text));

            command.Connection = connection;
            command.ExecuteNonQuery();
        }                
    }                
}

When I leave the textbox, I seem to get an error message stating

Invalid object name 'dbo.information'

when in fact the table is created as such in SQL Server:

CREATE TABLE [dbo].[information]
(
    [Id] NVARCHAR(50) NOT NULL PRIMARY KEY, 
    [password] NVARCHAR(50) NULL
)

So why is it a wrong name?

Upvotes: 0

Views: 618

Answers (2)

Jonatán Concha
Jonatán Concha

Reputation: 1

You are using the master database on your conection string.

You can change master for your own database:

Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;

Server=localhost\SQLEXPRESS01;Database=MyDataBase;Trusted_Connection=True;

Upvotes: 0

WhatsThePoint
WhatsThePoint

Reputation: 3635

I think the issue here could be a connection string issue.

Going off this example you are using a local database, here is an example connection string I have used in the past.

connectionString ="Data Source=.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True"

With initial catalog being the database name, and integrated security = true indicating to use windows authentication to the database.

So in your example it would look like this:

connectionString ="Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"/>

Like others mentioned in the comments don't create tables in the master database again, always create a new one.

And another note, a personal touch would be to look into configuration manager for you to store connection strings in, then you can easily call the connection string from there.

Upvotes: 1

Related Questions