2016-06-27 53 views
0

哎希望有人能幫助,要瘋了:-)DataAdapter.Update沒有更新

做一個小程序,再次得到數據集和更新它,我有以下SQLclass。數據集遍歷正常並且值被更改,但是dosnt會提交給數據庫。

class SQLConnection 
{ 
    private string SQL_String; 
    private string strCON; 
    System.Data.SqlClient.SqlDataAdapter da_1; 

    public string Sql { 
     set { SQL_String = value; } 
    } 

    public string connection_string 
    { 
     set { strCON = value; }  

    } 

    public System.Data.DataSet Getconnection 
    { 
     get { return Getmydataset(); } 

    } 

    private System.Data.DataSet Getmydataset() 
    { 
     System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCON); 

     con.Open(); 

     da_1 = new System.Data.SqlClient.SqlDataAdapter(SQL_String, con); 

     System.Data.DataSet dat_set = new System.Data.DataSet(); 
     da_1.Fill(dat_set, "Table_Data_1"); 



     return dat_set; 

    } 

    public void UpdateDatabase(System.Data.DataSet ds) 
    { 


     System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1); 

     int test = cb.DataAdapter.Update(ds.Tables[0]); 

    } 

} 
} 

當我調用類,並嘗試做更新的DataAdapter返回0

static public void Main(string[] args) 
    { 
       GetClosedComputers(); 
    } 

getclosedcomputers

public static DataSet GetClosedComputers() 
    { 
     try 
     { 
      SQLConnection objConnect = new SQLConnection(); 
      conString = Properties.Settings.Default.Connectionstring; 

      objConnect.connection_string = conString; 
      //call stored procedure 
      objConnect.Sql = Properties.Settings.Default.GetNextClosedComputers; 


      ds = objConnect.Getconnection; 


      ds.Tables[0].Columns["State"].Expression = "'1'"; 
      objConnect.UpdateDatabase(ds); 

     } 
     catch (Exception e) 
     { 
      ErrorString = e.Message; 

     } 
     return ds; 
    } 

回答

0

嗯,好像我不得不問題,首先我不能使用UpdateProcedure,我不知道爲什麼,也可以使用「.Expression」,這解決了它。

objConnect = new SQLConnection(); 
conString = Properties.Settings.Default.Connectionstring; 

objConnect.connection_string = conString; 
// use sql query instead of stored procedure!!! 
objConnect.Sql = Properties.Settings.Default.Test; 

//Dataset with all computers 
ds = objConnect.Getconnection; 

//DataSet results = StartStopVM.StartVirtualMachines(ds); 
DataTable dt = ds.Tables[0]; 

//this didnt work 
//ds.Tables[0].Columns["State"].Expression = "'1'"; 
// 
foreach(DataRow dr in dt.Rows) 
{ 
    dr["State"] = 1; 

} 
objConnect.UpdateDatabase(ds);