如何通过C#中的数据表将列添加到数据库(MS Access) [英] how to add a column to a database (MS Access) through Datatable in C#

查看:234
本文介绍了如何通过C#中的数据表将列添加到数据库(MS Access)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Datatable将列永久添加到数据库中,我希望像这样

how to add a column to a database permanently using Datatable I expect something like this

Projects.connection = new OleDbConnection(Projects.connectionstring);
         Projects.connection.Open();
         Projects.da = new OleDbDataAdapter(Projects.cmdstring, Projects.connection);
         Projects.dt = new DataTable();
         Projects.da.Fill(Projects.dt);
         Projects.dt.Columns.Add("new column name");
         Projects.cmdb = new OleDbCommandBuilder(Projects.da);


                 Projects.dt.GetChanges();



                 if (Projects.dt.GetChanges() != null)
                 {

                     Projects.da.Update(Projects.dt);
                     Projects.connection.Close();

                 }
                 Projects.dt.AcceptChanges();



但是很遗憾,数据库中未添加新列,请提供帮助.

在此先感谢



but unfortunately new column is not added in the database, please somebody help.

thanks in advance

推荐答案

不幸的是,这种方式无法正常工作.您将必须使用 ADO.NET [ ^ ] 命令对象 [ SqlCommand [
Unfortunately things do not work that way. You will have to use an ADO.NET[^] Command Object[^] (for example an SqlCommand[^]).
You will have to make a query that correctly inserts the column in your database table. The code for this is dependent on the type of database you are using. Pass this to the SqlCommand, together with a Connection Object and run the query. Be sure you can only do this once though. Every next time you try to run the command an Exception will be thrown that the Column already exists.
For this reason it is actually always better to have your columns defined at design time, because if you REALLY don''t know if you have the column or not all code you write should have to work with AND without that column.
Pseudo code for your problem:
if !(CheckIfMyColumnExists){
OleDbCommand cmd = new OleDbCommand("alter table MyTable add MyColumn int", myConn);
cmd.ExecuteNonQuery();
}
// Column should exist at this point.


尝试使用 ADOX

http://msdn.microsoft.com/zh-我们/library/windows/desktop/ms677200%28v=vs.85%29.aspx [ http://msdn.microsoft.com/zh-我们/library/windows/desktop/ms676514%28v=vs.85%29.aspx [ http://support.microsoft.com/kb/317881 [
Try to work with ADOX

http://msdn.microsoft.com/en-us/library/windows/desktop/ms677200%28v=vs.85%29.aspx[^]


http://msdn.microsoft.com/en-us/library/windows/desktop/ms676514%28v=vs.85%29.aspx[^]

And working with ADOX in csharp :
http://support.microsoft.com/kb/317881[^]


这篇关于如何通过C#中的数据表将列添加到数据库(MS Access)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆