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

时间:2013-06-05 06:24:14

标签: 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();
}

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

2 个答案:

答案 0 :(得分:5)

  

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

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

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

然后就简化而言:

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

答案 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();
}

希望它有用。