如何用c#连接visual studio 的localdb

weixin_38050219 2016-12-16 09:09:46

写个程序尝试用c#连接vs自带的localdb数据库,但是却无法连接。
  有时候会提示无法打开,提示的错误为:An attempt to attach an auto-named database for file c:\inetpub\wwwroot\Demo\App_Data\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
 有时候是ExecuteNonQuery()错误。但是我看帮助文件都所是数据库连接不正常导致的?代码如下
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace databaseconnect { class Program { static void Main(string[] args) { //判断数据库相对路径 string dataDir = AppDomain.CurrentDomain.BaseDirectory; if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\")) { dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName; AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); } //写入数据 SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\Database1.mdf; Integrated Security=True"); SqlCommand cmd = new SqlCommand(); // SqlDataAdapter adapter; con.Open(); cmd = new SqlCommand("insert into [table1] value (123,'name','state')",con); /*cmd.Parameters.AddWithValue("@id", "123"); cmd.Parameters.AddWithValue("@name", "tuidaods@qq.com"); cmd.Parameters.AddWithValue("@state", "haikou");*/ cmd.ExecuteNonQuery(); con.Close(); } } }


然后我测试了一下连接,显示连接是可以连接的
...全文
28 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38110510 2018-04-22
  • 打赏
  • 举报
回复
数据库版本是

please verify my account

谢谢你的回复

476

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧