【发布时间】:2017-11-25 20:24:01
【问题描述】:
我实际上是在尝试使用ExecuteScalar() 在插入后获取主键。因为它返回插入后第一行的第一列。但我得到了 0。我不知道为什么会这样。请帮帮我。
query = "Insert into Admissions(Admission_date, Student_name, Father_name, Mother_name, DOB, Gender, Address, State, City, Pincode, Admission_for, Previous_school, Fees) values ('" + txtAdmDate.Text + "','" + txtStudentName.Text + "','" + txtFatherName.Text + "','" + txtMotherName.Text + "','" + dob + "','" + gender + "','" + txtAddress.Text + "','" + txtState.Text + "','" + txtCity.Text + "','" + txtPincode.Text + "','" + cmbClass.Text + "','" + txtPreviousSchool.Text + "','" + txtFees.Text + "')";
cmd = new SqlCommand(query, con);
con.Open();
int admid = Convert.ToInt32(cmd.ExecuteScalar());
【问题讨论】:
-
SQL Injection alert - 您应该不将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看Little Bobby Tables
-
另外:
INSERT INTO不返回任何内容 - 因此,您得到 0。您需要有一个语句实际上 选择 从查询返回的内容,例如SELECT COUNT(*) .....或类似的东西
标签: c#