Connecting to local SQL Server database using C#

前端 未结 6 1840
后悔当初
后悔当初 2020-12-17 16:53

Suppose I have created a SQL Server database called Database1.mdf in the App_Data folder in Visual Studio with a table called Names. <

相关标签:
6条回答
  • 2020-12-17 16:55

    You try with this string connection

    Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
    
    0 讨论(0)
  • 2020-12-17 16:57

    If you're using SQL Server express, change

    SqlConnection conn = new SqlConnection("Server=localhost;" 
           + "Database=Database1;");
    

    to

    SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;" 
           + "Database=Database1;");
    

    That, and hundreds more connection strings can be found at http://www.connectionstrings.com/

    0 讨论(0)
  • 2020-12-17 17:02

    I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.

    Hope that helps.

    0 讨论(0)
  • 2020-12-17 17:04

    In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

    0 讨论(0)
  • 2020-12-17 17:09

    If you use SQL authentication, use this:

    using System.Data.SqlClient;
    
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = 
         "Data Source=.\SQLExpress;" + 
         "User Instance=true;" + 
         "User Id=UserName;" + 
         "Password=Secret;" + 
         "AttachDbFilename=|DataDirectory|Database1.mdf;"
    conn.Open();
    

    If you use Windows authentication, use this:

    using System.Data.SqlClient;
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = 
         "Data Source=.\SQLExpress;" + 
         "User Instance=true;" + 
         "Integrated Security=true;" + 
         "AttachDbFilename=|DataDirectory|Database1.mdf;"
    conn.Open();
    
    0 讨论(0)
  • 2020-12-17 17:09
    SqlConnection c = new SqlConnection(@"Data Source=localhost; 
                               Initial Catalog=Northwind; Integrated Security=True");
    
    0 讨论(0)
提交回复
热议问题