[英]How to deploy Windows app with SQL Server database?
我已經在Visual Studio 2012中使用SQL Server 2012數據庫開發了一個應用程序。 當我嘗試發布應用程序以對其進行測試時,它可以在我的計算機(包括SQL Server數據文件夾中的數據庫)上正常運行,但是當我將該發布的應用程序移動到另一台計算機上時,它將無法正常工作。
我想知道將項目及其數據庫一起部署的最簡單方法。 我已經看到了將SQL數據庫與我的應用程序集成的解決方案是使用localdb,但我不了解使用它的步驟。 我需要所有步驟來部署帶有SQL Server 2012數據庫的應用程序,以便將該應用程序安裝在另一台PC上,而不必在該PC上安裝SQL Server 2012。
您的應用無法在另一台計算機上運行,因為您在沒有數據庫的情況下以相同配置在本地計算機上部署了該應用。
如果您的計算機上沒有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>
似乎不久前我遇到了同樣的問題。 我查看了SQL Server,MySQL,SQL Server Express和SQL Server Compact版本。 我想要一個用於獨立應用程序的簡單數據庫。 SQL Server Compact適用於獨立的獨立數據庫。 對於獨立數據庫,SQLite是另一個絕佳選擇,但這是另一個答案。 SQL Server Express的優點/缺點已經在另一個答案中有所介紹。
要部署SQL Server Compact(CE),您可以包括SQLCE40Runtime_x86-ENU.exe
的安裝程序,也可以包括安裝程序為您手動創建的所需目錄和SQLCE40Runtime_x86-ENU.exe
。 有關更多部署信息,請參見: https : //msdn.microsoft.com/zh-cn/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 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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.