您好,欢迎访问三七文档
当前位置:首页 > IT计算机/网络 > C/C++资料 > 简单实用的DataSet更新数据库的类+总结(c#)
ÒÔÇ°¾³£ÓÃsqlÓï¾ä£¨update£©¸üÐÂÊý¾Ý¿â£¬ÓÐʹÓÃÓÃÆðÀ´²»ÊǺܷ½±ã£¬ÌرðÊÇÊý¾ÝÁ¿±È½Ï´óµÄÇé¿öÏ£¨±ÈÈçÊý¾Ý±í£©ºÜÂé·³~~ºóÀ´¸Ð¾õÓÃDataSet¸üÐÂÊý¾Ý¿âÊDz»´íµÄÑ¡Ôñ.ÓÚÊǼ±×ÅдÁËÒ»¸öÓÃataSet¸üÐÂÊý¾Ý¿âµÄÀàÈçÏ£º£¨ºóÃæÓÐʹÓÃ˵Ã÷£¬×ܽᣩusingSystem;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Windows.Forms;namespacewinApplication{publicclasssqlAccess{//ÓëSQLServerµÄÁ¬½Ó×Ö·û´®ÉèÖÃprivatestring_connString;privatestring_strSql;privateSqlCommandBuildersqlCmdBuilder;privateDataSetds=newDataSet();privateSqlDataAdapterda;publicsqlAccess(stringconnString,stringstrSql){this._connString=connString;}privateSqlConnectionGetConn(){try{SqlConnectionConnection=newSqlConnection(this._connString);Connection.Open();returnConnection;}catch(Exceptionex){MessageBox.Show(ex.Message,Êý¾Ý¿âÁ¬½Óʧ°Ü);throw;}}//¸ù¾ÝÊäÈëµÄSQLÓï¾ä¼ìË÷Êý¾Ý¿âÊý¾ÝpublicDataSetSelectDb(stringstrSql,stringstrTableName){try{this._strSql=strSql;this.da=newSqlDataAdapter(this._strSql,this.GetConn());this.ds.Clear();this.da.Fill(ds,strTableName);returnds;//·µ»ØÌî³äÁËÊý¾ÝµÄDataSet£¬ÆäÖÐÊý¾Ý±íÒÔstrTableName¸ø³öµÄ×Ö·û´®ÃüÃû}catch(Exceptionex){MessageBox.Show(ex.Message,Êý¾Ý¿â²Ù×÷ʧ°Ü);throw;}}//Êý¾Ý¿âÊý¾Ý¸üÐÂ(´«DataSetºÍDataTableµÄ¶ÔÏó)publicDataSetUpdateDs(DataSetchangedDs,stringtableName){try{this.da=newSqlDataAdapter(this._strSql,this.GetConn());this.sqlCmdBuilder=newSqlCommandBuilder(da);this.da.Update(changedDs,tableName);changedDs.AcceptChanges();returnchangedDs;//·µ»Ø¸üÐÂÁ˵ÄÊý¾Ý¿â±í}catch(Exceptionex){MessageBox.Show(ex.Message,Êý¾Ý¿â¸üÐÂʧ°Ü);throw;}}ʹÓÃ˵Ã÷×ܽ᣺1.GetConn·½·¨´´½¨Ò»¸öÊý¾Ý¿âÁ¬½Ó£¬·µ»ØSqlConnection¡£2.ʹÓõÄselectÃüÁîÖбØÐë°üº¬Ö÷¼ü£¬Õâµã´ó¼Ò¶¼ÖªµÀµÄ!3.this.da.Fill(ds,strTableName)Ìî³äÊý¾Ý¼¯4.¹¹ÔìCommandBuilder¶ÔÏóʱ,½«DataAdapter¶ÔÏó×÷Ϊ¹¹Ô캯Êý²ÎÊý´«Èë:this.sqlCmdBuilder=newSqlCommandBuilder(da);5.ÔÚµ÷ÓÃUpdateDs()¸üÐÂÊý¾Ý¿âÇ°£¬Çë¼ì²échangedDsÊÇ·ñÒѾ±»¸üйý£¬ÓÃchangedDs.[tableName]GetChanges()!=null;6.ÓÃthis.da.Update(changedDs,tableName)·½·¨¸üÐÂÊý¾Ý,È»ºóµ÷ÓÃchangedDs.AcceptChanges()²ÅÄÜÕæÕýµÄ¸üÐÂÊý¾Ý¿â£¬µ÷ÓÃchangedDs.RejectChanges()È¡Ïû¸üС£
本文标题:简单实用的DataSet更新数据库的类+总结(c#)
链接地址:https://www.777doc.com/doc-7028944 .html