无法插入数据

时间:2014-09-04 13:57:25

标签: c# asp.net sql-server

我无法找到错误,为什么我的数据没有插入数据库中。我用的是sql server。 DB是3字段:1)id(int)2)test1(varchar(50))3)test2(varchar(50))。我尝试从文本框和日期插入数据。

private void SaveToDB()
    {
        string strSql = "";
        string[] tos = txtTo.Text.Split(';');
        for (int i = 0; i < tos.Length; i++)
        {
            strSql += "INSERT INTO test (test1, test2) VALUES ('" + txtContent.Text.Trim() + "','" + DateTime.Now.ToString() + "');";
        }
        using (SqlConnection connection = new SqlConnection(Common.ConnetionString))
        {
            connection.Open();
            SqlTransaction tran = connection.BeginTransaction();
            try
            {
                SqlCommand cmd = new SqlCommand(strSql, connection, tran);
                cmd.ExecuteNonQuery();
                tran.Commit();
            }
            catch (Exception e)
            {
                tran.Rollback();  
            }
            finally
            {
                connection.Close();
                Response.Redirect("messagelist.aspx?flag=2");
            }
        }
    }

但我应该如何更改代码,该参数在循环中工作

1 个答案:

答案 0 :(得分:1)

你的循环应该包含整个块。此外,参数化您的查询,以便您不会大开注射。只是一个建议,但我也会在你的sql语句中使用BEGIN TRANSACTION而不是SqlTransaction tran,它会为你处理回滚并稍微清理你的代码。

string[] tos = txtTo.Text.Split(';');
for (int i = 0; i < tos.Length; i++)
{
    string strSql = "INSERT INTO test (test1, test2) VALUES (@Content, @DateTime);";
    using (SqlConnection connection = new SqlConnection(Common.ConnetionString))
    {
        connection.Open();
        SqlTransaction tran = connection.BeginTransaction();
        try
        {
            using (SqlCommand cmd = new SqlCommand(strSql, connection, tran))
            {
                cmd.Parameters.AddWithValue("@Content", txtContent.Text.Trim());
                cmd.Parameters.AddWithValue("@DateTime", DateTime.Now.ToString());
                cmd.ExecuteNonQuery();
                tran.Commit();
            }
        }
        catch (Exception e)
        {
            tran.Rollback();  
        }
        finally
        {
            connection.Close();
            Response.Redirect("messagelist.aspx?flag=2");
        }
    }
}