如何将SQL数据库嵌入/附加到Visual C#中?

Ton*_* Wu 9 c# sql sql-server visual-studio-2010

这是我第一次使用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");
Run Code Online (Sandbox Code Playgroud)
  • 我可以将数据源嵌入到我的程序中,并将与其余解决方案一起编译吗?

关于该计划的一些额外背景;

这是一个需要搜索数据库中的6个表并输出DataRow搜索字符串匹配特定字段时的内容的程序.

例如.

Field 1     Field 2
quick       AA
brown       AA
fox         AB
jumps       AB
over        AA
the         AB
lazy        AB
dog         AA
Run Code Online (Sandbox Code Playgroud)

Search_String = AB

输出;

fox
jumps
the
lazy
Run Code Online (Sandbox Code Playgroud)

任何帮助都感激不尽!!!!!

谢谢

Sor*_*scu 8

只是为了获得一个抓地力(VS 2010):

  1. 创建一个控制台项目
  2. 添加对System.Data.SqlServerCe的引用(在我的计算机上的Program Files\Microsoft SQL Server Compact Edition\v3.5\Desktop\System.Data.SqlServerCe.dll中)
  3. 在解决方案资源管理器中右键单击项目节点,选择"添加=>新项...",选择"本地数据库",将其命名为MyDB
  4. 新文件MyDB.sdf将添加到项目中(MS SQL Server Compact数据库)
  5. 右键单击新文件,单击"打开",数据库将在"服务器资源管理器"中打开
  6. 在"服务器资源管理器"中展开MyDB.sdf,右键单击Tables,"Create Table"(将其命名为MyTable)
  7. 添加两列"Field1"和"Field2"(暂时保留nvarchar(100))
  8. 右键单击新表,选择"显示表数据",填写您的数据

代码:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将输出狐狸跳懒惰.

但是,出于简单的目的,我会选择SQlite.包装器在这里:http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki