protected void populateDataGrid()
{
string connectionString = configurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string command = "select * from student";
SqlDataAdapter dataAdapter = new SqlDataAdapter(command, connectionString);
DataSet data = new DataSet();
dataAdapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = @"INSERT INTO [student] (studentID, studentFirstName, studentLastName)
VALUES (" + TextID.Text + ", '" + TextFirstName.Text + "', '" + TextLastName.Text + "')";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
第一个函数获取所有表数据并将其转储到gridview。 第二个函数接受输入并将其插入数据库。 如何压缩或简化这些功能?
答案 0 :(得分:5)
如何简化或简化这些功能?
在简化之前,我会专注于正确性。目前我可以看到代码中至少有两个问题:
using
语句,以便即使抛出异常,连接和命令也会自动关闭。然后就简化而言:
SqlCommand
构造函数来获取文本和连接 - 无论如何,类型默认为Text
。答案 1 :(得分:3)
在Button2_Click(object sender, EventArgs e)
方法中,您需要使用参数化查询来避免SQL Injection。
这是标准方式。
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = @"INSERT INTO [student] (
studentID, studentFirstName, studentLastName
) VALUES (
@studID, @FName, @LName
)";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Parameters.AddWithValue("@studID", TextID.Text);
cmd.Parameters.AddWithValue("@FName", TextFirstName.Text);
cmd.Parameters.AddWithValue("@LName", TextLastName.Text);
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
}
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
希望它有用。