asp.net在while循环中将数据插入SQL Server数据库

时间:2012-03-06 18:24:44

标签: c# asp.net sql-server import

我想将Excel工作表中的数据导入SQL Server数据库(2008)。我已经成功测试了从xls文件获取数据的代码。但是,我无法将这些数据插入到db表中。以下是代码的一部分:

        while (ctecka.Read())
        {
            exJmeno = ctecka[0].ToString();
            exPrijmeni = ctecka[1].ToString();
            Response.Write(exJmeno + " " + exPrijmeni + " ");
            pridano = vlozSQL.ExecuteNonQuery();
        }

ctecka 是DbDataReader对象,它包含来自excel工作表的数据

exJmeno exPrijmeni 是字符串,列中的数据会插入其中

问题:

Response.write 将我需要的数据写到页面上

vlozSQL.ExecuteNonQuery 忽略(exJmeno和exPrijmeni)中的数据并将空列插入数据库中的表

这里有一些定义:

string InsertSQL = "INSERT INTO users (name, surname) VALUES (@name,@surname)";
vlozSQL.Parameters.AddWithValue("@name", exJmeno);
vlozSQL.Parameters.AddWithValue("@surname", exPrijmeni);

编辑

    string exJmeno = "";
    string exPrijmeni = "";
    string InsertSQL = "INSERT INTO users (name, surname) VALUES (@name,@surname)";
    SqlConnection sqlconn = new SqlConnection(SQLpripoj);
    SqlCommand vlozSQL = new SqlCommand(InsertSQL, sqlconn);
    vlozSQL.Parameters.AddWithValue("@name", exJmeno);
    vlozSQL.Parameters.AddWithValue("@surname", exPrijmeni);

    try
    {
        spojeni.Open();
        DbDataReader ctecka = prikaz.ExecuteReader();

        sqlconn.Open();
        while (ctecka.Read())
        {
            exJmeno = ctecka[0].ToString();
            exPrijmeni = ctecka[1].ToString();
            Response.Write(exJmeno + " " + exPrijmeni + " ");
            pridano = vlozSQL.ExecuteNonQuery();
        }
    }
    finally
    {
        spojeni.Close();
        sqlconn.Close();
        Label2.Text = pridano.ToString();
    }

2 个答案:

答案 0 :(得分:1)

由于字符串在C#中不可变,因此循环中的赋值实际上不会更改参数,您每次都必须添加它们。你需要做类似的事情;

while (ctecka.Read())
{
    exJmeno = ctecka[0].ToString();
    exPrijmeni = ctecka[1].ToString();
    Response.Write(exJmeno + " " + exPrijmeni + " ");
    vlozSQL.Parameters.Clear();
    vlozSQL.Parameters.AddWithValue("@name", exJmeno);
    vlozSQL.Parameters.AddWithValue("@surname", exPrijmeni);
    pridano = vlozSQL.ExecuteNonQuery();
}

答案 1 :(得分:1)

在while循环中移动这部分代码

vlozSQL.Parameters.AddWithValue("@name", exJmeno);
vlozSQL.Parameters.AddWithValue("@surname", exPrijmeni);

代表:

while (ctecka.Read())
    {
        exJmeno = ctecka[0].ToString();
        exPrijmeni = ctecka[1].ToString();
        vlozSQL.Parameters.AddWithValue("@name", exJmeno);
         vlozSQL.Parameters.AddWithValue("@surname", exPrijmeni);
        Response.Write(exJmeno + " " + exPrijmeni + " ");
        pridano = vlozSQL.ExecuteNonQuery();
    }