今天做一个WinForm程序,在写入数据时出现以下问题:
(1)access设计数据库是不能用关键字做为字段名,
(2)添加数据时CommandBuilder对DataAdapter进行封装才能执行成功!!
代码如下,两种方法对数据库写进录入:
using System; using System.Data.OleDb; using System.Data; namespace zzzDemo { ///
/// ConnDAO 的摘要说明。
///
public class ConnDAO { //数据连接
private OleDbConnection oConn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:/OrderSystem.mdb'"); private OleDbDataAdapter oda = null; private OleDbCommandBuilder cb = null; //private DataTable dt = new DataTable("Dictionary1");
private DataSet ds = new DataSet(); public ConnDAO() { oConn.Open(); oda = new OleDbDataAdapter("select * from Dictionary1",oConn); oda.Fill(ds,"dd"); oConn.Close(); } //添加数据方法
public bool addDictionary(Dictionary dy) { //第一种解决方法
/*oda.InsertCommand = new OleDbCommand(); oda.InsertCommand.CommandText = "insert into Dictionary1(Category,CValue) values('"+dy.Category+"','"+dy.Value+"')"; oda.InsertCommand.Connection = oConn; oConn.Open(); int i = oda.InsertCommand.ExecuteNonQuery(); oConn.Close(); if(i>0) return true; else return false;*/
//第二种解决方法
cb = new OleDbCommandBuilder(oda); //一定要用CommandBuilder进行封装
DataRow dr = ds.Tables["dd"].NewRow(); dr["Category"] = dy.Category; dr["CValue"] = dy.Value;
ds.Tables["dd"].Rows.Add(dr); ds.Tables["dd"].GetChanges(); oConn.Open(); int i = oda.Update(ds.Tables["dd"]); oConn.Close(); if(i>0) return true; else return false; } //返回DataTable表
public DataTable GetDictionary() { return ds.Tables["dd"]; }
public static void Main(string[]args) { //测试
ConnDAO dao = new ConnDAO(); Dictionary dd = new Dictionary(); dd.Category = "ccc"; dd.Value = "555"; bool falg = dao.addDictionary(dd); Console.WriteLine(falg); }
} public class Dictionary { private string _Category; private string _Value; public string Category { get{return _Category;} set{_Category = value;} } public string Value { get{return _Value;} set{_Value = value;} }
} }
|
阅读(5178) | 评论(0) | 转发(0) |