使用sql连接的最佳/标准方法是什么?

use*_*370 2 c# asp.net sqlconnection

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();
}
Run Code Online (Sandbox Code Playgroud)

第一个函数获取所有表数据并将其转储到gridview.第二个函数接受输入并将其插入数据库.如何压缩或简化这些功能?

Jon*_*eet 5

如何压缩或简化这些功能?

在简化之前我会专注于正确性.目前我可以看到代码中至少有两个问题:

  • 绝对应该使用参数化SQL而不是将值放入SQL本身.您当前的代码容易受到SQL注入攻击.
  • 您应该使用using语句,以便即使抛出异常,连接和命令也会自动关闭.

然后就简化而言:

  • 您可以使用SqlCommand带有文本和连接的构造函数 - Text无论如何都是默认类型.
  • 我个人会尝试将UI代码与存储代码分开,至少对于一个非平凡的项目.您应该查看ASP.NET MVC,至少要了解分离,即使您没有更改以开始使用它.