如何编写SQL连接字符串?

时间:2012-10-30 11:09:27

标签: asp.net sql connection

我将此作为我的连接字符串属性:

Data Source="c:\users\perdanny\documents\visual studio 2012\Projects\WebApplication1\WebApplication1\App_Data\Users.sdf"

现在,我应该如何在我的代码中编写它:

sqlConnection = new SqlConnection(???);

3 个答案:

答案 0 :(得分:0)

试试这个:

string strConnection = ConfigurationManager.ConnectionStrings["Name of connection string key"].ConnectionString;  

// Or, for a quick test you could also use
// string strConnection = "Data Source = c:\\users\\perdanny\\documents\\visual studio 2012\\Projects\\WebApplication1\\WebApplication1\\App_Data\\Users.sdf"     

  using (var conn = new SqlCeConnection(string.Format("Data Source={0}", strConnection)))
  {
     conn.Open();

     try
     {
         System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
         cmd.CommandType = System.Data.CommandType.StoredProcedure;
         cmd.CommandText = "Your sql stored proc name";
         cmd.Connection = conn ;
         cmd.ExecuteNonQuery();     
     }
     catch (SqlCeException)
     {
         throw;
     }
     finally
     {
         if (conn.State == ConnectionState.Open) conn.Close();
     }
  }

答案 1 :(得分:0)

string connStr = ConfigurationManager.ConnectionStrings [“connectionString”]。ToString();

<add name="connectionString" connectionString="Data Source=SQLEXPRESS;Initial Catalog=dbsql;User ID=hello;Password=hello"
      providerName="System.Data.SqlClient" />

答案 2 :(得分:-1)

使用ConfigurationManager和

查看下面的代码行:

string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;