1

在下面的代码中,我调用了一个方法以及对列表的引用来保存每个对象的所有数据,如姓名、年龄、性别和信息,但是在我测试了我的应用程序之后,表是空的!我错过了什么或做错了吗?我没有错误。

public void SaveDataToDB(List<Animal> animals)
    {
        connection = new SqlConnection(connectionString);
        dataset = new DataSet();
        sql = "SELECT * From Guests";

        try
        {
            connection.Open();
            adapter = new SqlDataAdapter(sql, connection);
            adapter.Fill(dataset, "Guests");

            foreach (Animal animal in animals)
            {
                DataRow row = dataset.Tables["Guests"].NewRow();
                row["Name"] = animal.Name;
                row["Age"] = animal.Age;
                row["Gender"] = animal.Gender;
                row["Info"] = animal.ImportantInfo;

                dataset.Tables["Guests"].Rows.Add(row);
            }
            new SqlCommandBuilder(adapter);
            adapter.Update(dataset.Tables["Guests"]);
            connection.Close();
        }
        catch
        {
            throw;
        }
    }
4

1 回答 1

1

为了使您的插件正常工作,您需要InsertCommand为适配器定义一个。这是示例:

public void SaveDataToDB(List<Animal> animals)
{
    SqlConnection connection = new SqlConnection(connectionString);
    DataSet dataset = new DataSet();
    string sql = "SELECT * From Guests";

    try
    {
        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
        adapter.Fill(dataset, "Guests");

        // Create the InsertCommand.
        SqlCommand command = new SqlCommand(
            "INSERT INTO Guests (Name, Age, Gender, ImportantInfo) " +
            "VALUES (@Name, @Age, @Gender, @ImportantInfo)", connection);

        // Add the parameters for the InsertCommand.
        command.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
        command.Parameters.Add("@Age", SqlDbType.Int, 4, "Age");
        command.Parameters.Add("@Gender", SqlDbType.NVarChar, 6, "Gender");
        command.Parameters.Add("@ImportantInfo", SqlDbType.NVarChar, 100, "ImportantInfo");

        foreach (Animal animal in animals)
        {
            DataRow row = dataset.Tables["Guests"].NewRow();
            row["Name"] = animal.Name;
            row["Age"] = animal.Age;
            row["Gender"] = animal.Gender;
            row["Info"] = animal.ImportantInfo;

            dataset.Tables["Guests"].Rows.Add(row);
        }
        new SqlCommandBuilder(adapter);
        adapter.Update(dataset.Tables["Guests"]);
        connection.Close();
    }
    catch
    {
        throw;
    }
}

确保为 db 参数指定实际的 db 类型和大小。

于 2012-08-02T12:05:38.057 回答