如何用c#连接visual studio 的localdb
写个程序尝试用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();
}
}
}
然后我测试了一下连接,显示连接是可以连接的