using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class Student_InsertStudentDeta : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblMsg.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
btnDelete.Enabled = false;
btnFindValuse.Enabled = false;
btnUpdate.Enabled = false;
SqlConnection connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
connection.Open();
SqlCommand cmd = new SqlCommand("Insert into MoHE_Student values (N'" + txtName.Text + "',N'" + txtSureName.Text + "',N'" + txtFatherName.Text + "',N'" + txtGFatherName.Text + "',N'" + txtBirthYear.Text + "',N'" + txtNIDC.Text + "',N'" + txtTabdily.Text + "',N'" + txtTitalMonugraf.Text + "',N'" + ddlJeldBook.SelectedItem.Text + "',N'" + txtDescription.Text + "',N'" + ddlUniversity.SelectedItem.Value + "',N'" + ddlFaculty.SelectedItem.Value + "',N'" + ddlDepartment.SelectedItem.Value + "'," + txtStudentRegBook.Text + "," + txtPageBook.Text + "," + ddlReciveBook.SelectedItem.Text + "," + txtGraduateYear.Text + "," + txtRegYear.Text + ",N'" + ddlKoncurExam.SelectedItem.Text + "',N'" + ddlDefaMonugraf.SelectedItem.Text + "',N'" + ddlYearDefa.SelectedItem.Text + "',N'" + ddlMonthDefa.SelectedItem.Text + "',N'" + ddlDayDefa.SelectedItem.Text + "',N'" + ddlTakeDiplom.SelectedItem.Text + "',N'" + txtPhonNum.Text + "',N'" + ddlGender.SelectedItem.Text + "',N'" + ddlDarajaTahsili.SelectedItem.Text + "',N'" + User.Identity.Name + "')", connection);
cmd.ExecuteNonQuery(); // Error happens here
}
}
答案 0 :(得分:0)
副本解释了什么是错的,这是多么严重以及如何避免它。我不会在这里重复解释,因为我开始了,然后我的手指开始刺痛。复制品的各种答案都足够,甚至包含Bobby Tables
。
这只是展示了如何修复这个特定的代码。
首先,命令可以创建一次并重复使用:
SqlCommand _insertCmd;
void InitCommands()
{
_connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var query = "Insert into MoHE_Student values (@name,@surname,...";
var cmd = new SqlCommand(query);
cmd.Parameters.Add("@name",SqlDbType.NVarChar,30);
cmd.Parameters.Add("@surname",SqlDbType.NVarChar,30);
...
_insertCmd=cmd;
}
当需要执行时,设置参数值并在使用块中打开连接,以确保即使发生错误也会关闭连接:
_insertCmd["@name"].Value=txtName.Text;
...
using(var connection = new SqlConnection(_connectionString))
{
_insertCmd.Connection=connection;
connection.Open();
_insertCmd.ExecuteNonQuery();
}