在我的下面的代码中,我调用一个方法以及对列表的引用来保存每个对象的名称,年龄,性别和信息等所有数据,但在我测试了我的应用程序之后,该表是空的!我错过了什么或做错了吗?我没有错。
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;
}
}
答案 0 :(得分: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类型和大小。