1)需要将.NET Framework 4更新至至少4.0.2。If you have 4.0.2, then you should have
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\SKUs\.NETFramework,Version=v4.0.2
如果您已经安装了最新的VS 2012有机会,你已经有4.0.2。先验证一下。
2)接下来你需要有一个LocalDb
的实例。默认情况下,您有一个实例,其名称是一个v
字符,后跟LocalDB版本号,格式为xx.x.例如,v11.0
代表SQL Server 2012. Automatic instances are public by default. You can also have named instances which are private。命名实例提供与其他实例的隔离,并可通过减少与其他数据库用户的资源争用来提高性能。 You can check the status of instances using the SqlLocalDb.exe
utility (run it from command line).
3)接下来您的连接字符串应该是这样的:
"Server=(localdb)\\v11.0;Integrated Security=true;"
从您的代码
或
"Data Source=(localdb)\\test;Integrated Security=true;"
。 They both are the same.注意两个\\
需要,因为\v
和\t
表示特殊字符。另请注意,在(localdb)\\
之后出现的是LocalDb实例的名称。 v11.0
是默认的公共实例,test
是我手动创建的私有的。
如果你有一个数据库(.mdf文件)已经:
"Server=(localdb)\\Test;Integrated Security=true;AttachDbFileName= myDbFile;"
如果你没有一个SQL Server数据库:
"Server=(localdb)\\v11.0;Integrated Security=true;"
而且您可以创建自己的数据库程序化盟友:
一)将其保存在默认设置的默认位置:
var query = "CREATE DATABASE myDbName;";
B)要使用自己的自定义设置,将其保存在一个特定的位置:
// your db name
string dbName = "myDbName";
// path to your db files:
// ensure that the directory exists and you have read write permission.
string[] files = { Path.Combine(Application.StartupPath, dbName + ".mdf"),
Path.Combine(Application.StartupPath, dbName + ".ldf") };
// db creation query:
// note that the data file and log file have different logical names
var query = "CREATE DATABASE " + dbName +
" ON PRIMARY" +
" (NAME = " + dbName + "_data," +
" FILENAME = '" + files[0] + "'," +
" SIZE = 3MB," +
" MAXSIZE = 10MB," +
" FILEGROWTH = 10%)" +
" LOG ON" +
" (NAME = " + dbName + "_log," +
" FILENAME = '" + files[1] + "'," +
" SIZE = 1MB," +
" MAXSIZE = 5MB," +
" FILEGROWTH = 10%)" +
";";
并执行!
样本表可以加载到数据库的东西,如:
@"CREATE TABLE supportContacts
(
id int identity primary key,
type varchar(20),
details varchar(30)
);
INSERT INTO supportContacts
(type, details)
VALUES
('Email', '[email protected]'),
('Twitter', '@sqlfiddle');";
注意SqlLocalDb.exe
实用犯规让你访问数据库,则需要分别sqlcmd
工具,它是可悲的..
编辑:移动分号的位置,否则错误会发生如果代码被复制/粘贴
我并不是说这是问题的原因,是因为可能会有更多,但反斜杠在C#字符串中是特殊的,除非你在它们前面加上'@':'@“(LocalDB)\ v11.0”'。 – hvd
是的,我没有添加@符号。我做了重试并返回了相同的结果。 –
连接字符串中没有数据库。 –