我正在尝试将数据插入数据库。我找不到我的impfectedResults为0的任何原因,并且不断崩溃,这使我对cmd.ExecuteNonQuery()产生了很大的困扰,它说“((。)附近有不正确的语法”,所以我仔细分析了我的过去一个小时的sql语句,我不太确定问题出在哪里。
private int SendData(string sqlStatement)
{
SqlConnection conn = new SqlConnection(Properties.Settings.Default.cnnString);
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
int AffectedRecords = 0;
using (conn)
{
conn.Open();
AffectedRecords = cmd.ExecuteNonQuery();
conn.Close();
}
return AffectedRecords;
}
private void InsertData()
{
string sql = string.Format("INSERT INTO Participant (LastName, FirstName, " + ("Country, Gender, IACMember, Rank, SponsorId" +
"VALUES (\'{0}\',\'{1}\',\'{2}\',\'{3}\','{4}',{5}, {6})"),
txtLastName.Text, txtFirstName.Text, cboCountry.SelectedItem, Gender(gender),
(chkMember.Checked), ((txtRank.Text == string.Empty) ? "Null" : txtRank.Text),
((cboSponsor.Text == "No Sponsor") ? "Null" : cboSponsor.SelectedValue));
SendData(sql);
}
答案 0 :(得分:0)
为什么不以简单的方式插入数据?您也将自己暴露在SQL INJECTIONS
之下。这是方法
private int InsertData()
{
int AffectedRecords = 0;
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.cnnString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Participant (LastName, FirstName, Country, Gender, IACMember, Rank, SponsorId) VALUES (@LastName, @FirstName, @Country, @Gender, @IACMember, @Rank, @SponsorId)", con))
{
con.Open();
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("@Country", cboCountry.SelectedItem);
//Your Remaining Fields
AffectedRecords = cmd.ExecuteNonQuery();
}
}
return AffectedRecords;
}