connection()
{
OleDbConnection nwindConn=new OleDbConnection();
MySql.Data.MySqlClient.MySqlConnection con= new MySqlConnection();
MySqlCommand cmd;
con.ConnectionString ="server=localhost;" +
"uid=root;"+
"pwd=;" +
"database=globasys;" ;
DateTime dt=DateTime.Now;
string select = "SELECT CategoryID, CategoryName FROM categories";
MySqlDataAdapter catDA = new MySqlDataAdapter(select, con);
string insert = "insert into categories(CategoryID,CategoryName)
VALUES(@CategoryID,@CategoryName)
ON DUPLICATE KEY UPDATE [email protected]";
catDA.InsertCommand = new MySqlCommand(insert, con);
catDA.InsertCommand.Parameters.Add("@CategoryID", MySqlDbType.Int32
, 11, "CategoryID");
catDA.InsertCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar
, 250, "CategoryName");
DataSet catDS = new DataSet();
catDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
catDA.Fill(catDS, "Categories");
DataSet newdt = new DataSet();
newdt = getnewdata();
int i= catDA.Update(newdt, "Categories");
}
public DataSet getnewdata()
{
DataSet catDS=new DataSet();
DataTable dt = new DataTable();
DataColumn col1 = new DataColumn("CategoryID", typeof(int));
dt.Columns.Add(col1);
DataColumn col=new DataColumn("CategoryName",typeof(string));
dt.Columns.Add(col);
DataColumn[] Cols = { dt.Columns[0] };
dt.PrimaryKey =Cols;
DataRow crow = dt.NewRow();
crow["CategoryID"]=1;
crow["CategoryName"]="io";
dt.Rows.Add(crow);
dt.TableName = "Categories";
DataRow crow1 = dt.NewRow();
crow1["CategoryID"] = 3;
crow1["CategoryName"] = "p";
dt.Rows.Add(crow1);
dt.TableName = "Categories";
catDS.Tables.Add(dt);
return catDS;
}
我希望插入命令ON DUPLICATE KEY UPDATE
用新值更新旧值。如果这些值不存在,那么它需要插入一个新值。使用ON DUPLICATE KEY UPDATE更新插入查询已存在row
它不会执行,但不更新现有的值
考虑我的表
1 a
2 b
使用此查询
INSERT INTO categories(CategoryID,CategoryName)
VALUES(1,qq) ON DUPLICATE KEY UPDATE CategoryID = 1
然后我想要的结果是
1 qq
2 b