如何将数据插入数据库

时间:2015-02-18 02:47:23

标签: c# wpf

单击按钮保存时如何将数据插入数据库?

  

Xaml add

<TextBox Name="NRIC"/>
<TextBox Name="VisitorName"/>
<TextBox Name="ReasonVisit"/>
<TextBox Name="CardID"/>
<TextBox Name="CardPin"/>

<Button Content="Save" Name="SaveData"Click="SaveData_Click"/>
  

背后的代码

private void SaveData_Click(object sender, RoutedEventArgs e)
{
    var connectionString = new ConnectionString();
    var conn = new SqlConnection(connectionString.ViMS_LOCAL());
    string query = "SELECT VisitorNo,Name,NRIC,Reason,CardID,CardPin FROM dbo.[Visitor.Profile]";

    try
    {
        conn.Open();
        //??
    }
    catch (Exception err)
    {
    }
    finally
    {
        conn.Close();
    }
}

1 个答案:

答案 0 :(得分:2)

首先,您需要更改查询。区分InsertSelect

string query = "INSERT INTO 
                    [Visitor.Profile] (VisitorNo, Name, NRIC, Reason, CardID, CardPin)
                VALUES
                    (@VisitorNo, @Name, @NRIC, @Reason, @CardID, @CardPin)";

之后你需要使用SqlCommand。

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.Parameters.AddWithValue("@VisitorNo", "Here Value for the Number in current question it is not specify from where to take it. Probably this is int or guid you should have a way to set next int or new guid");
        cmd.Parameters.AddWithValue("@Name", VisitorName.Text);
        cmd.Parameters.AddWithValue("@NRIC", NRIC.Text);
        cmd.Parameters.AddWithValue("@Reason", ReasonVisit.Text);
        cmd.Parameters.AddWithValue("@CardID", CardID.Text);
        cmd.Parameters.AddWithValue("@CardPin", CardPin.Text);

        cmd.ExecuteNonQuery();
    }
    catch (Exception err)
    {
        //do something with the exception !
    }
    finally
    {
        conn.Close();
    }