添加了未保存在访问数据库中的数据列



我想编写代码将数据列添加到数据表,但是当我保存数据表时,它不包括新的数据列。

它保存我添加的任何新数据行,但不保存数据列。

有人可以告诉我我做错了什么吗?

public partial class Form1 : Form
{
    MyDatabase DB;
    DataTable Products;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        DB = new MyDatabase();
        DB.Open(@"C:UsersGrantDocumentsDatabase.accdb");
        Products = DB.GetTable("Products");
        AddColumn();
        AddRow();
        DB.Save(Products);
    }
    private void AddColumn()
    {
        DataColumn Column = new DataColumn();
        Column.DataType = Type.GetType("System.String");
        Column.ColumnName = "TestColumn";
        Products.Columns.Add(Column);
    }
    private void AddRow()
    {
        DataRow Row;
        Row = Products.Rows.Add(1, "B", "C");
    }
}
class MyDatabase
{
    // The following program has to be installed on the computer
    // http://www.microsoft.com/downloads/en/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
    private String provider = "Microsoft.ACE.OLEDB.12.0";
    private String source;
    private OleDbConnection connection;
    private String connectionString;
    private DataSet dataSet = new DataSet();
    private OleDbDataAdapter adapter;
    private OleDbCommandBuilder commandBuilder;
    public String Provider
    {
        get { return provider; }
        set { provider = value; }
    }
    public String Source
    {
        get { return Source; }
        set { source = value; }
    }
    public void Open(String Filename)
    {
        connectionString = @"Provider=" + provider + @";Data Source=" + Filename;
        connection = new OleDbConnection(connectionString);
        connection.Open();
        adapter = new OleDbDataAdapter();
    }
    public void BuildStrings()
    {
        commandBuilder = new OleDbCommandBuilder(adapter);
        adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
        adapter.InsertCommand = commandBuilder.GetInsertCommand();
        adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
    }
    public DataTable GetTable(String TableName)
    {
        adapter.SelectCommand = new OleDbCommand("SELECT * From " + TableName, connection);
        BuildStrings();
        adapter.Fill(dataSet, TableName);
        return dataSet.Tables[TableName];
    }
    public void Save(DataTable Table)
    {
        adapter.Update(Table);
        adapter.Update(dataSet, "Products");
    }
}

从其他论坛得到答案。

您不能使用数据集或数据表向数据库表添加新的列/字段,您可能需要将"ALTER TABLE"与 ADO.NET 命令一起使用。查看以下链接

如何使用 SqlDataAdapter 和数据表将新列插入数据库表?[^]

使用 VB 中的 SQL 表添加列 ADO.NET 命令[^]

相关内容

  • 没有找到相关文章

最新更新