将不同设备上的同一应用程序连接到同一数据库
本文关键字:应用程序 连接 数据库 | 更新日期: 2023-09-27 18:30:16
我有一个 C# winforms 应用程序,我想将其安装在两个或更多设备上,但我希望他们共享同一个数据库。关于如何做到这一点的任何建议?
你的问题太笼统了,所以我试着给你一般性的答案。
您可能正在尝试为更多共享数据库和数据的用户创建应用程序。可能最好的选择是在服务器上公开您的共享数据库(按目的 - lan 或 wan)并从每个设备连接到它。
你应该提到你正在使用哪个数据库,例如MySQL,MSSQL,...
另一件事是,如果您希望在每个设备上都有一个数据库,这些数据库可以离线修改并以时间间隔同步,但我认为这不是解决这种情况的好方法。
在您提供更多信息后,我将进行更新。
编辑:你必须做的第一件事 - 公共MSSQL服务器,以便应用程序将从能够pingMSSQL服务器的设备启动。其次,您从应用程序创建与它的连接,我为您提供示例,您应该根据您的情况对其进行修改以达到最佳目的(例如 - 而不是为每个查询创建一个连接,您应该使用连接池、事务的使用等......
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
public class Program
{
static void Main()
{
string Query = "SELECT * FROM [MyTable]";
//db connection config
DbConfigInfo Config = new DbConfigInfo()
{
ServerAddress = "MyServer",
DbName = "MyDb",
TrustedConnection = true
};
//db adapter for communication
DbAdapter Adapter = new DbAdapter()
{
DbConfig = Config
};
//output with data
DataTable MyDataTable;
if (!Adapter.ExecuteSqlCommandAsTable(Query, out MyDataTable))
{
Console.WriteLine("Error Occured!");
Console.ReadLine();
return;
}
//do actions with your DataTable
}
}
public class DbAdapter
{
//keeps connection info
public DbConfigInfo DbConfig { get; set; }
public bool ExecuteSqlCommandAsTable(string CmdText, out DataTable ResultTable)
{
ResultTable = null;
try
{
using (SqlConnection Conn = new SqlConnection(DbConfig.GetConnectionStringForMssql2008()))
{
SqlCommand Cmd = new SqlCommand(CmdText, Conn);
Conn.Open();
SqlDataReader Reader = Cmd.ExecuteReader();
DataTable ReturnValue = new DataTable();
ReturnValue.Load(Reader);
ResultTable = ReturnValue;
return true;
}
}
catch (Exception e)
{
return false;
}
}
}
public class DbConfigInfo
{
public string ServerAddress { get; set; } //address of server - IP address or local name
public string DbName { get; set; } //name of database - if you want create new database in query, set this to master
public string User { get; set; } //user name - only if winauth is off
public string Password { get; set; } //user password - only if winauth is off
public bool TrustedConnection { get; set; } //if integrated windows authenticating under currently logged win user should be used
//creates conn string from data
public string GetConnectionStringForMssql2008()
{
StringBuilder ConStringBuilder = new StringBuilder();
ConStringBuilder.AppendFormat("Data Source={0};", ServerAddress)
.AppendFormat("Initial Catalog={0};", DbName);
if (TrustedConnection)
{
ConStringBuilder.Append("Trusted_Connection=True;");
}
else
{
ConStringBuilder.AppendFormat("User Id={0};", User)
.AppendFormat("Password={0};", Password));
}
return ConStringBuilder.ToString();
}
}