问题描述
winform界面上有两个textbox分别用于输入工程名称,工程编号,四个comboBox用于输入工程级别,两个dateTimePicker输入生产日期,在my_db中已建了一个数据表”新建项目“,希望通过界面上的创建button,将textbox这些空间中的内容存入这个数据表中对应的内容下面
privatevoidbutton1_Click(objectsender,EventArgse){OleDbConnectionConn=newOleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=F:\my_db.mdb");Conn.Open();stringsql;OleDbCommandcmd=newOleDbCommand("",Conn);if(newtextBox1.Text!=""){sql="select*from新建项目where项目编号='"+newtextBox1.Text.Trim()+"'";cmd.CommandText=sql;if(null==cmd.ExecuteScalar()){sql="insertinto新建项目values('"+newtextBox1.Text.Trim()+"','"+项目名称textBox2.Text.Trim()+"','"+comboBox1.Text.ToString()+"','"+comboBox2.Text.ToString()+"','"+comboBox3.Text.ToString()+"','"+comboBox4.Text.ToString()+"','"+dateTimePicker1.Value.ToString()+"','"+dateTimePicker2.Value.ToString()+"')";cmd.CommandText=sql;cmd.ExecuteNonQuery();MessageBox.Show("项目创建成功");}elseMessageBox.Show("已有重名角色存在","提示");}elseMessageBox.Show("角色名称不能为空");Conn.Close();}最后没有达到预期效果,未处理oledbexception
解决方案
解决方案二:
Winform连接access数据库操作(1)access设计数据库是不能用关键字做为字段名,(2)添加数据时CommandBuilder对DataAdapter进行封装才能执行成功!!代码如下,两种方法对数据库写进录入:usingSystem;usingSystem.Data.OleDb;usingSystem.Data;namespacezzzDemo{//////ConnDAO的摘要说明。///publicclassConnDAO{//数据连接privateOleDbConnectionoConn=newOleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource='D:/OrderSystem.mdb'");privateOleDbDataAdapteroda=null;privateOleDbCommandBuildercb=null;//privateDataTabledt=newDataTable("Dictionary1");privateDataSetds=newDataSet();publicConnDAO(){oConn.Open();oda=newOleDbDataAdapter("select*fromDictionary1",oConn);oda.Fill(ds,"dd");oConn.Close();}//添加数据方法publicbooladdDictionary(Dictionarydy){//第一种解决方法/*oda.InsertCommand=newOleDbCommand();oda.InsertCommand.CommandText="insertintoDictionary1(Category,CValue)values('"+dy.Category+"','"+dy.Value+"')";oda.InsertCommand.Connection=oConn;oConn.Open();inti=oda.InsertCommand.ExecuteNonQuery();oConn.Close();if(i>0)returntrue;elsereturnfalse;*///第二种解决方法cb=newOleDbCommandBuilder(oda);//一定要用CommandBuilder进行封装DataRowdr=ds.Tables["dd"].NewRow();dr["Category"]=dy.Category;dr["CValue"]=dy.Value;ds.Tables["dd"].Rows.Add(dr);ds.Tables["dd"].GetChanges();oConn.Open();inti=oda.Update(ds.Tables["dd"]);oConn.Close();if(i>0)returntrue;elsereturnfalse;}//返回DataTable表publicDataTableGetDictionary(){returnds.Tables["dd"];}publicstaticvoidMain(string[]args){//测试ConnDAOdao=newConnDAO();Dictionarydd=newDictionary();dd.Category="ccc";dd.Value="555";boolfalg=dao.addDictionary(dd);Console.WriteLine(falg);}}publicclassDictionary{privatestring_Category;privatestring_Value;publicstringCategory{get{return_Category;}set{_Category=value;}}publicstringValue{get{return_Value;}set{_Value=value;}}}}