c# connect to sql using attachdb

来源:互联网 发布:homebrew mysql 密码 编辑:程序博客网 时间:2024/05/22 04:55

a. database

     App_Data/test.mdf

bwebconfig

<connectionStrings>

<add name="test1Con" connectionString="Data Source=.\SQLEXPRESS;

         AttachDBFilename=|DataDirectory|test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

     providerName="System.Data.SqlClient" />

 </connectionStrings>

c. c#

protected void Button_Click(object sender, EventArgs e) {            SqlConnection con=null;            SqlCommand cmd;            SqlDataReader dr;            try            {                string strcon = ConfigurationManager.ConnectionStrings["test1Con"].ToString();                con = new SqlConnection(strcon);                cmd = con.CreateCommand();                cmd.CommandText = "select * from a";                con.Open();                dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);                if (dr.Read())                {                    string s = Convert.ToString(dr[0]);                }            }            catch (Exception ex)            {                throw ex;            }            finally            {                con.Close();            }}

d. config

application pool

->create new application pool for .net framework v2.0

->set the name of the new application name to any name

->right click and choose advance settings

->set process model to Integrated

->set identification to localsystem

->set your website to this application pool

->restart you webapplication and it will be ok

e. error will occur without the config above

Please make sure the user has a local user profile on the computer.

<finish>