ADO.NET问题写入数据库

时间:2012-01-31 03:38:16

标签: c# database ado.net

我正在尝试使用下面的代码插入数据库,我已经尝试了所有我能想到的但是当我检查数据库中的表时没有任何变化,我做错了什么?

P.S如下所示,数据库名称为Stoichiometry.mdb,表格名称为Molecules。

由于

 con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Stoichiometry.mdb");
    adMol = new OleDbDataAdapter();
    adMol.SelectCommand = new OleDbCommand("SELECT * FROM Molecules", con);

    dsHistory = new DataSet();
    con.Open();
    adMol.Fill(dsHistory, "Molecules");
    con.Close();

    DataRow data = dsHistory.Tables["Molecules"].NewRow();
    data["Formula"] = formula_;
    data["MolecularWeight"] = totalWeight_;
    adMol.InsertCommand = new OleDbCommand("INSERT INTO Molecules (Formula,"
                    + " MolecularWeight) " + "VALUES(@Formula, @MolecularWeight)", con);


    adMol.InsertCommand.Parameters.Add("@Formula", OleDbType.VarChar, 250, "Formula");
    adMol.InsertCommand.Parameters["@Formula"].SourceVersion = DataRowVersion.Current;
    adMol.InsertCommand.Parameters.Add("@MolecularWeight", OleDbType.Numeric, 20, "MolecularWeight");
    adMol.InsertCommand.Parameters["@MolecularWeight"].SourceVersion = DataRowVersion.Current;

1 个答案:

答案 0 :(得分:3)

添加参数后添加此行

adMol.InsertCommand.ExecuteNonQuery();

更新

adMol.InsertCommand = new OleDbCommand("INSERT INTO Molecules (Formula," + " MolecularWeight) " + "VALUES(@Formula, @MolecularWeight)", con);
adMol.InsertCommand.Parameters.Add("@Formula", OleDbType.VarChar, 250, "Formula");
adMol.InsertCommand.Parameters["@Formula"].SourceVersion = DataRowVersion.Current;
adMol.InsertCommand.Parameters.Add("@MolecularWeight", OleDbType.Numeric, 20, "MolecularWeight");
adMol.InsertCommand.Parameters["@MolecularWeight"].SourceVersion = DataRowVersion.Current;
adMol.InsertCommand.ExecuteNonQuery()