C#/ WPF - 保存对MySQL的更改

时间:2014-05-27 10:23:13

标签: c# wpf xaml

我正在写一个小测试应用程序。它只是一个XAML视图,带有两个绑定到MySQL表的文本框。我可以很好地阅读数据,但我不知道如何保存更改并可以提供一些帮助:

XAML:

<TextBox Text="{Binding org_name}" HorizontalAlignment="Left" Height="26" Margin="139,9,0,0" VerticalAlignment="Top" Width="339" FontWeight="Bold" FontSize="{DynamicResource appFontSize}" />
    <TextBox Text="{Binding adr_one_postalcode}" HorizontalAlignment="Left" Height="26" Margin="868,92,0,0" VerticalAlignment="Top" Width="110" FontSize="{DynamicResource appFontSize}" />

C#

//Initial variables
readonly MySqlConnection _con = new MySqlConnection(ClsVariables.StrDb);
readonly RecordReturn _rec = new RecordReturn();
MySqlCommand _cmd;
MySqlDataReader _dr;


private void Window_ContentRendered(object sender, EventArgs e)
{
    _con.Open();
    var sqlText = string.Format("SELECT view_source.* FROM view_source WHERE view_source.contact_id = " + ClsVariables.IntId + ";");
    var sqlCmd = new MySqlCommand(sqlText, _con);
    using (var reader = sqlCmd.ExecuteReader())
{
    if (reader.Read())
    {
    _rec.contact_id = ClsVariables.IntId.ToString();
    _rec.org_name = reader["org_name"] as string;
    _rec.adr_one_postalcode = reader["adr_one_postalcode"] as string;
    }
}
    _con.Close();
    DataContext = _rec;
}


private class RecordReturn
{
    public string contact_id { [UsedImplicitly] private get; set; }
    public string org_name { [UsedImplicitly] private get; set; }
    public string adr_one_postalcode { [UsedImplicitly] private get; set; }
}

2 个答案:

答案 0 :(得分:1)

您可以添加按钮&#34;保存&#34;并执行此代码。

using(_con)
{
    using(SqlCommand cmd = new SqlCommand("UPDATE Table SET col1 = @par1, col2 = @par2 WHERE id = @id", _con))
    {
        cmd.Parameters.AddWithValue("@par1", TextBox1.Text);
        cmd.Parameters.AddWithValue("@par2", TextBox2.Text);
        cmd.Parameters.AddWithValue("@id", _selectedID);

        cmd.ExecuteNonQuery();
    }
}

编辑: 此外,在代码的循环中,它应该是while(rdr.Read()),而不是if(rdr.Read())

答案 1 :(得分:0)

正如你暗示的那样,如果你有50个字段(或者100个,或者500个......),那么上面给出的手动方法实际上会变得很快(并且容易出错)。

你可能是初学者,但我真的建议你看看两件事:Entity Framework和MVVM。

  1. 第一个提供您的数据访问,并将可怕的选择/更新魔术字符串转换为LINQ查询,只更新真实类对象的属性。
  2. 第二个将向您展示如何将表示数据的对象绑定到UI中的元素,这样当UI更改时,类对象的属性中保存的数据也会更改。然后,您可以提交&#39;这些更改使用EF,因此简化了将更改写入数据库的方式。