Connecting to a Service-Based Datasource in C#

2019-09-20 00:57发布

This is a very noobish question:

I don't understand SQL. I'm trying to make a generic connection to an empty SQL database in C#. I don't want to make tables in advance, I just want to be able to open the connection.

Every "connectionstring" I try results in "InvalidOperationException" so I need some help understanding the proper syntax to connect to a SQL data file in Visual Studio.

What I have done is gone to "Add -> New Item -> Service-based Database"

This gives me a "Database1.mdf" in the solution explorer.

Now I want to open a connection through C# to this file at which point I can use SQL strings to manipulate the file.

I believe the next step is to use: SQLConnection SQLConn = new SQLConnection(" ... ");

But I don't know what to put for the "server" or the "database" in the connectionstring.

Can someone tell me the most basic way to connect to a "Service-based Datasource" in C#?

Will this "service-based database" be included in the final compile? E.g. if I compile a finished executable, will each installation come with its own local SQL database?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-09-20 01:19

The service based database will not be embedded in the dll. See the last section of the below (in bold) to see how to obtain the connection string.

From an MSDN article (http://msdn.microsoft.com/en-us/library/vstudio/ms233763%28v=vs.110%29.aspx):

To create a project and a database file:

  1. Create a Windows Forms project that's named SampleDatabaseWalkthrough.

    See Creating Solutions and Projects.

  2. On the menu bar, choose Project, Add New Item.

    The Add New Item dialog box appears so that you can add items that are appropriate in a windows Form project.

  3. In the list of templates, scroll down until Service-based Database appears, and then choose it.

  4. Name the database SampleDatabase, and then choose the Add button.

    The Data Source Configuration Wizard opens.

  5. On the Choose a Database Model page, choose the Dataset icon, and then choose the Next button.

  6. On the Choose Your Database Objects page, no database objects are available because the database is new.

  7. Choose the Finish button to create the database and dataset and add them to the project.

    The properties window for the database shows the connection string and the location of the primary .mdf file for the database. To display this window, choose the Server Explorer tab, expand the Data Connections node, open the shortcut menu for the database, and then choose Properties.

查看更多
登录 后发表回答