如何将SQL数据库嵌入/附加到Visual C#中?
这是我第一次使用SQL,这可能是一个愚蠢的问题,但我做了一些研究,我不认为我找到了我正在寻找的东西。
我想要的是一种制作将在我的C#程序中使用的私有SQL数据库的方法。 我已经在SQL Server Express中创建了一个数据库,并将其连接到Visual Studio 2010。
SqlCommand DBAccess = new SqlCommand(); DBAccess.Connection = new SqlConnection( "Data Source = localhost;" + "Initial Catalog = My_Database;" + "Trusted_Connection = True");
- 我可以将数据源嵌入到我的程序中,并将与其余解决方案一起编译吗?
关于该计划的一些额外背景;
这是一个程序,需要搜索数据库中的6个表,并在搜索字符串与特定字段匹配时输出DataRow
的内容。
例如。
Field 1 Field 2 quick AA brown AA fox AB jumps AB over AA the AB lazy AB dog AA
Search_String = AB
输出;
fox jumps the lazy
任何帮助都感激不尽!!!!!
谢谢
只是为了获得一个抓地力(VS 2010):
- 创建一个控制台项目
- 添加对System.Data.SqlServerCe的引用(在我的计算机上的Program Files \ Microsoft SQL Server Compact Edition \ v3.5 \ Desktop \ System.Data.SqlServerCe.dll中)
- 在Solution Explorer中右键单击项目节点,选择“Add => New Item …”,选择“Local Database”,将其命名为MyDB
- 新文件MyDB.sdf将添加到项目中(MS SQL Server Compact数据库)
- 右键单击新文件,单击“打开”,数据库将在“服务器资源管理器”中打开
- 在“服务器资源管理器”中展开MyDB.sdf,右键单击Tables,“Create Table”(将其命名为MyTable)
- 添加两列“Field1”和“Field2”(暂时保留nvarchar(100))
- 右键单击新表,选择“显示表数据”,填写您的数据
代码:
using System.Data.SqlServerCe; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { using (var cn = new SqlCeConnection("Data Source=MyDB.sdf")) { cn.Open(); using (var cmd = cn.CreateCommand()) { cmd.CommandText = "select * from MyTable where Field2 like '%AB%'"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine("Field1: {0}", reader[0]); } } } } Console.ReadKey(); } } }
将输出狐狸跳懒惰。
但是 ,出于简单的目的,我会选择SQlite 。 包装器在这里: http : //system.data.sqlite.org/index.html/doc/trunk/www/index.wiki
是的,为此目的有http://en.wikipedia.org/wiki/SQL_Server_Compact 。
SQLite非常好用,速度快,重量轻……
您将需要查看SQL Server Compact Edition