我尝试了代码,但失败了,因为从本地数据库插入时,远程数据库中的行重复了。
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行必须插入到远程数据库中。如何避免这个问题?
1条答案
按热度按时间5gfr0r5j1#
将上次保存的用户id存储在本地数据库中,当您再次转到远程数据库同步数据时,请在查询where remotedb.userid>local.laststoreduserid中放入where子句。所以它只能获取新的记录。。。