简体   繁体   中英

my database path in "Data Source=F:\databas1.mdf; How to set database connection in c# website?

Below My Database connection path but I can't connect to database

 SqlConnection cn = new SqlConnection("Data Source=.F:\Database.mdf");   
 SqlCommand cmd = new SqlCommand("SELECT * FROM stu1", cn);  
 SqlDataAdapter adp = new SqlDataAdapter(cmd);  
 DataSet ds = new DataSet();
 adp.Fill(ds);  
 GridView1.DataSource = ds.Tables[0];   
 GridView1.DataBind();

A great resource I always keep around is connectionstrings.com . It's really handy for finding these connection strings when you can't find an example.

Particularly this page applied to your problem

Attach a database file on connect to a local SQL Server Express instance

Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=F:\Database.mdf"; Database=dbname;Trusted_Connection=Yes;

Put this in your code, as per your database:

 connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DB Name;User ID=sa;Password=test";


 SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM stu1", ConnectionString);  
 DataSet ds = new DataSet();
 adp.Fill(ds, "stu1");  
 GridView1.DataSource = ds.Tables[0];   
 GridView1.DataBind();

Try this out and let me know if you face any issue. I hope it will help you to resolve your issue. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM