我尝试了代码,但由于从本地数据库插入时远程数据库中的行重复而失败。
using System.Data.SQLite;
using System.Net.NetworkInformation;
using MySql.Data.MySqlClient;
namespace super
{
public partial class neworupload : Form
{
SQLiteConnection con = new SQLiteConnection(@"connection string");
MySqlConnection conn;
String connstring;
public neworupload()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool connection = NetworkInterface.GetIsNetworkAvailable();
if (connection == true)
{
connstring = "SERVER=your ip;PORT=port;DATABASE=dbname;UID=userid;PASSWORD=password;SslMode = none;";
try
{
con.Open();
MessageBox.Show("Connection success");
String qu = "select * from users ";
SQLiteCommand cmd = new SQLiteCommand(qu, con);
SQLiteDataReader data = cmd.ExecuteReader();
while (data.Read())
{
String a = data["iduser"].ToString();
String b = data["name"].ToString();
String c = data["type"].ToString();
String d = data["email"].ToString();
String f = data["hash"].ToString();
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(f);
conn = new MySqlConnection();
conn.ConnectionString = connstring;
conn.Open();
String qudemo = "select iduser from users";
Console.WriteLine("dddd" + qudemo);
String qu1 = "INSERT INTO users(iduser,name,type,email,hash) Values(@iduser,@name,@type,@email,@hash)";
MySqlCommand cmd1 = new MySqlCommand(qu1, conn);
cmd1.Parameters.AddWithValue("@iduser", a);
cmd1.Parameters.AddWithValue("@name", b);
cmd1.Parameters.AddWithValue("@type", c);
cmd1.Parameters.AddWithValue("@email", d);
cmd1.Parameters.AddWithValue("@hash", f);
cmd1.ExecuteNonQuery();
conn.Close();
}
con.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex);
}
}
else
{
MessageBox.Show("Check connectivity and try again!");
}
}
}
}
此处本地数据库包含7行,远程数据库包含5行。本地和远程数据库中的前5行相同。因此,当我们插入查询时,由于行重复而失败。实际上,必须将额外的2行插入到远程数据库中。如何避免这个问题?
答案 0 :(得分:0)
将上次保存的用户ID存储在本地数据库中,当您再次转到远程数据库以同步数据时,将此where子句放在查询 where RemoteDB.UserID> local.LastStoredUserID 中。因此它只会获取新记录...