【问题标题】:How to deploy Windows app with SQL Server database?如何使用 SQL Server 数据库部署 Windows 应用程序?
【发布时间】:2015-06-09 18:47:58
【问题描述】:

我在 Visual Studio 2012 中使用 SQL Server 2012 数据库开发了一个应用程序。当我尝试发布应用程序来测试它时,它在我的机器上正常工作(包括 SQL Server 数据文件夹中的数据库),但是当我将该已发布的应用程序移动到另一台机器上时它就不起作用了。

我想知道将项目及其数据库一起部署的最简单方法。 我已经看到将 SQL 数据库与我的应用程序集成的解决方案是使用 localdb,但我不明白使用它的步骤。 我需要使用 SQL Server 2012 数据库部署应用程序的所有步骤,以便在另一台 PC 上安装该应用程序,而无需在该 PC 上安装 SQL Server 2012。

【问题讨论】:

  • 您可以使用/部署 SQL Server Compact Edition。见:msdn.microsoft.com/en-us/library/aa983326%28v=vs.140%29.aspx
  • SQL Server Compact Edition的扩展名是.sdf,那么如何将sql server 2012导出为.sdf?
  • SQL Server Compact Edition 不会更新,并且限制在较新版本的 Visual Studio 中没有内置支持。 LocalDb 是该类型部署的新推动力。您需要在目标机器上安装运行时并部署您需要的文件。

标签: c# database visual-studio-2012 sql-server-2012 localdb


【解决方案1】:

您的应用无法在另一台机器上运行,因为您在没有数据库的本地机器上使用相同的配置部署了它。

  • 如果您的计算机上没有 SQL Server,您可以使用 SQL Server Express(默认情况下它与 Visual Studio 一起安装,除非您明确告诉它不要这样做)并更新 web.config

    <connectionStrings>
        <add name="testCon" 
             connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" 
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
    
  • 将数据库部署到服务器并更改连接字符串

    <connectionStrings>
        <add name="testCon" 
             providerName="System.Data.SqlClient" 
             connectionString="Data Source=Server_Name;Initial Catalog=DB_Name; User Id=User_Name;Password=Password;" /> 
    </connectionStrings>
    

【讨论】:

  • 我是 Visual Studio 和 sql server 的新手,我需要一步一步来(我没看懂你说的。)。
  • 我的应用程序类型是 windows (winform) 与 sql server 2012 中的数据库连接现在我需要创建我的应用程序的 .exe(包含数据库)才能安装应用程序其他电脑上的数据库,无需在其他电脑上安装sql server。谢谢
  • 在新机器上部署应用程序后,您还需要获取数据库或将数据库部署到服务器(从当前数据库获取副本)并更改连接以让您的应用程序连接到您当前的服务器无法从本地计算机外部访问数据库,因此当新计算机上的应用程序尝试连接时失败
  • 现在我需要使用数据库部署我的应用程序,以便在另一台电脑上直接安装应用程序(包含数据库)。
  • 您可以使用 Visual Studio 默认安装的 SQLEXPRESS,您只需获取“Database.mdf”,您将在“C:\Program Files\Microsoft SQL Server\MSSQL10_50. MSSQLSERVER\MSSQL\DATA" 从您的本地计算机连接到它,如我在回答中声明的那样
【解决方案2】:

似乎不久前我遇到了同样的问题。我查看了 SQL Server、MySQL、SQL Server Express 和 SQL Server Compact 版本。我想要一个用于独立应用程序的简单数据库。 SQL Server Compact 适合独立、自包含的数据库。 SQLite 是独立数据库的另一个绝佳选择,但这是另一个答案。 SQL Server Express 的优缺点已经在另一个答案中介绍过。

要部署 SQL Server Compact (CE),您可以包含 SQLCE40Runtime_x86-ENU.exe 的安装程序,也可以包含安装程序为您手动创建的所需目录和 Dll。更多部署信息见:https://msdn.microsoft.com/en-us/library/aa983326%28v=vs.140%29.aspx

我将使用的连接字符串是

ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\DevEssai.sdf;Persist Security Info=False";

有关连接字符串的其他想法,请参阅:http://www.connectionstrings.com/

你最终做出的任何选择,你必须做出的每个选择都有利有弊。无论哪种方式,都需要您进行一些研究才能为您的应用程序选择最佳选择。不要被吓倒。一旦你进一步研究它,它并不像你最初想象的那么难。这只是每个人都必须经历的学习曲线。

【讨论】:

  • 如果我选择 SQL Compact Edition,我需要从 sql server 2012 导出数据库,扩展名为 (.sdf),我有代码项目 (codeproject.com/Articles/25685/…) 的解决方案将 .mdf 转换为 .sdf但我不明白如何使用。
  • 啊啊啊,也许不在那个项目上。它需要旧版本的 SQL compact,并且需要大量工作才能得到有问题的结果。我的建议是自己动手。创建一个转换例程来读取现有的 SQL 数据库记录并立即将它们写入 SQL 紧凑记录。熟悉使用 SQL CE 将是一个很好的练习,并且应该是一个相对简单的读写例程。
  • 在我创建的下一个答案中查看我的示例。
  • 但我需要更改解决方案中的表名和查询名以及数据库名
  • 是的,这只是供您使用或学习的示例。您现有的表名和数据库名可以保持不变。 SQL CE 数据库具有 .sdf 扩展名,而 SQL 数据库具有 .mdf 扩展名。除此之外,编码差异很小。
【解决方案3】:

我创建了一个简单的转换程序来将我的一个 SQL Server 表转换为一个 SQL Server Compact Edition 表。我刚刚创建了一个带有“转换”按钮的 Windows 窗体。它将创建 SQL Server CE 数据库,然后从 SQL Server 数据库表中读取每条记录,并将其写入 SQL Server Compact 数据库中的等效表记录。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.Data.SQLite;

namespace SampleConversion
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            string cmd = "";
            int count = 0;

            create_SQLCE_database(); // Create the SQL Server CE database file and a table within it

            string SQLconnectionString = "server=(local); database=PTHData; Trusted_Connection=True;"; // open PTHData.mdf
            string SQLCEconnectionString = "Data Source=" + Application.StartupPath + "\\pthData.sdf;Persist Security Info=False"; // open PTHDATA.sdf

            // open the input and output database
            SqlCeConnection SQLCEconnection = new SqlCeConnection(SQLCEconnectionString);

            try
            {
                SQLCEconnection.Open();
            }
            catch (SqlCeException ex)
            {
                string errorMessages = "A SQL Server CE exception occurred on open.\n" + ex.Message;
                MessageBox.Show(errorMessages, "Convert");
                return;
            }
            SqlConnection SQLconnection = new SqlConnection(SQLconnectionString);
            try
            {
                SQLconnection.Open();
            }
            catch (SqlException ex)
            {
                string errorMessages = "A SQL exception occurred on open.\n" + ex.Message;
                MessageBox.Show( errorMessages, "Convert");
                return;
            }

            //Databases are not open, time to convert
            SqlCommand cmdread = new SqlCommand();
            cmdread.Connection = SQLconnection;
            cmdread.CommandText = "Select * from USTimeZones";
            SqlDataReader drread = null;

            SqlCeCommand cmdwrite = new SqlCeCommand();
            cmdwrite.Connection = SQLCEconnection;

            try
            {
                drread = cmdread.ExecuteReader();
                while (drread.Read())
                {
                    drread["timezone"].ToString();
                    cmd = "Insert into USTimeZones values ('" + drread["state"].ToString() + "','" +
                        drread["city"].ToString() + "','" + drread["county"].ToString() + "','" +
                        drread["timezone"].ToString() + "','" + drread["timetype"].ToString() + "','" +
                        drread["latitude"].ToString() + "','" + drread["longitude"].ToString() + "')";
                    cmdwrite.CommandText = cmd;
                    try
                    {
                        cmdwrite.ExecuteNonQuery();
                        count++;
                    }
                    catch (SqlCeException ex)
                    {
                        string errorMessages = "A SQL exception occurred on writing the SQL Server CE record.\n" + ex.Message;
                        MessageBox.Show(errorMessages, "Convert");
                        SQLCEconnection.Close();
                        SQLconnection.Close();
                        return;
                    }

                }
            }
            catch (SqlException ex)
            {
                string errorMessages = "A SQL exception occurred reading records.\n" + ex.Message;
                MessageBox.Show(errorMessages, "Convert");
            }
            catch (Exception ex)
            {
                string errorMessages = "A General exception occurred reading records.\n" + ex.Message;
                MessageBox.Show(errorMessages, "Convert");
            }

            MessageBox.Show("Records written: " + count.ToString(), "Conversion complete");
            drread.Close();
            SQLconnection.Close();
            SQLCEconnection.Close();
        }

        private void create_SQLCE_database()
        {
            string connectionString = "Data Source=" + Application.StartupPath + "\\pthData.sdf;Persist Security Info=False";

            try
            {
                SqlCeEngine en = new SqlCeEngine(connectionString);
                en.CreateDatabase();
            }
            catch (SqlCeException ex)
            {
                MessageBox.Show("Unable to create the SQL Server CE pthData database\n" + ex.Message, "Create SQL Server CE file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to create the SQL Server CE pthData database\n" + ex.Message, "Create SQL Server CE file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }

            // file created, now create tables
            SqlCeConnection cn = new SqlCeConnection(connectionString);
            if (cn.State == ConnectionState.Closed)
                cn.Open();

            SqlCeCommand cmd;
            string commandString = "Create table USTimeZones\n";

            // create USTimeZones file
            commandString = "Create table USTimeZones\r\n";
            commandString += "(state nvarchar(30), city nvarchar(100), county nvarchar(50), timezone nvarchar(10), ";
            commandString += "timetype int, latitude nvarchar(10), longitude nvarchar(10),  ";
            commandString += "PRIMARY KEY(state, city, county, timezone, timetype))";
            cmd = new SqlCeCommand(commandString, cn);

            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SqlCeException sqlexception)
            {
                MessageBox.Show(sqlexception.Message + "\n Command string: " + commandString, "Error creating USTimeZoness", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error creating USTimeZones", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }

            cn.Close();
        }

    private void btnSQLiteConvert_Click(object sender, EventArgs e)
    {
        string cmd = "";
        int count = 0;

        create_SQLite_database(); // Create the SQLite database file and a table within it

        string SQLconnectionString = "server=(local); database=PTHData; Trusted_Connection=True;"; // open PTHData.mdf
        string SQLiteconnectionString = "Data Source=" + Application.StartupPath + "\\pthData.sqlite;Version=3;";

        // open the input and output database
        SQLiteConnection SQLiteconnection = new SQLiteConnection(SQLiteconnectionString);

        try
        {
            SQLiteconnection.Open();
        }
        catch (SQLiteException ex)
        {
            string errorMessages = "A SQLite exception occurred on open.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
            return;
        }

        SqlConnection SQLconnection = new SqlConnection(SQLconnectionString);

        try
        {
            SQLconnection.Open();
        }
        catch (SqlException ex)
        {
            string errorMessages = "A SQL exception occurred on open.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
            return;
        }

        //Databases are not open, time to convert
        SqlCommand cmdread = new SqlCommand();
        cmdread.Connection = SQLconnection;
        cmdread.CommandText = "Select * from USTimeZones";

        SqlDataReader drread = null;

        SQLiteCommand cmdwrite = new SQLiteCommand();
        cmdwrite.Connection = SQLiteconnection;

        try
        {
            drread = cmdread.ExecuteReader();

            while (drread.Read())
            {
                drread["timezone"].ToString();
                cmd = "Insert into USTimeZones values ('" + drread["state"].ToString() + "','" +
                    drread["city"].ToString() + "','" + drread["county"].ToString() + "','" +
                    drread["timezone"].ToString() + "','" + drread["timetype"].ToString() + "','" +
                    drread["latitude"].ToString() + "','" + drread["longitude"].ToString() + "')";
                cmdwrite.CommandText = cmd;

                try
                {
                    cmdwrite.ExecuteNonQuery();
                    count++;
                }
                catch (SQLiteException ex)
                {
                    string errorMessages = "An SQL exception occurred on writing the SQLite record.\n" + ex.Message;
                    MessageBox.Show(errorMessages, "Convert");
                    SQLiteconnection.Close();
                    SQLconnection.Close();
                    return;
                }

            }
        }
        catch (SqlException ex)
        {
            string errorMessages = "A SQL exception occurred reading records.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
        }
        catch (Exception ex)
        {
            string errorMessages = "A General exception occurred reading records.\n" + ex.Message;
            MessageBox.Show(errorMessages, "Convert");
        }

        MessageBox.Show("Records written: " + count.ToString(), "Conversion complete");
        drread.Close();
        SQLconnection.Close();
        SQLiteconnection.Close();
    }

    private void create_SQLite_database()
    {
        string connectionString = "Data Source=" + Application.StartupPath + "\\pthData.sqlite;Version=3;";

        try
        {
            SQLiteConnection.CreateFile("pthData.sqlite");
        }
        catch (SQLiteException ex)
        {
            MessageBox.Show("Unable to create the SQLite database\n" + ex.Message + "\nConnection string: " + connectionString, "Create SQLite file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to create the SQLitedatabase\n" + ex.Message + "\nConnection string: " + connectionString, "Create SQLite file/database error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
        // file created, now create tables
        SQLiteConnection cn = new SQLiteConnection(connectionString);
        if (cn.State == ConnectionState.Closed)
            cn.Open();

        SQLiteCommand cmd;
        string commandString = "Create table if not exists USTimeZones\n";

        // create time zones file
        commandString += "(state nvarchar(30), city nvarchar(100), county nvarchar(50), timezone nvarchar(10), ";
        commandString += "timetype int, latitude nvarchar(10), longitude nvarchar(10),  ";
        commandString += "PRIMARY KEY(state, city, county, timezone, timetype))";

        cmd = new SQLiteCommand(commandString, cn);

        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (SQLiteException sqlexception)
        {
            MessageBox.Show(sqlexception.Message + "\n Command string: " + commandString, "Error creating USTimeZones", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + "\n Command string: " + commandString, "Error creating USTimeZoness", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多