2013-07-20 4 views
0

// C#의 한 트랜잭션에서 여러 sqlcommands를 exceute하는 방법.이 코드를 사용하지만 error..plz로 인해 코드에 어떤 문제가 있는지 알려줍니다. .오류 : 트랜잭션이 완료되었습니다. 더 이상 사용할 수 없습니다.

string[] files = Directory.GetFiles(dir); 

foreach (string subfiles in files) 
{ 
    con.Open(); 
    SqlTransaction myTrans=null; 
    myTrans= con.BeginTransaction(); 


    try 
    { 

     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = con; 
     cmd.Transaction = myTrans; 
     cmd.CommandText = "select descr from genlookup where Code='SS_Purchase_No' and RecId=99998"; 

     SqlDataReader drr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
     DataTable dt = new DataTable(); 
     //SqlDataAdapter da = new SqlDataAdapter(qry1, con); 

     DataTable dtw = new DataTable(); 
     dtw.Load(drr); 
     DataSet dsr = new DataSet(); 
     dsr.Tables.Add(dtw); 
     //SqlDataAdapter darun = new SqlDataAdapter("select descr from genlookup where Code='SS_Purchase_No' and RecId=99998", con); 
     //DataSet dsr = new DataSet(); 
     //darun.Fill(dsr); 
     int run_no = Convert.ToInt32(dsr.Tables[0].Rows[0]["descr"].ToString()); 

     filename = Path.GetFileNameWithoutExtension(subfiles); 
     string filenames = Path.GetFileName(subfiles); 


     if (subfiles.Trim().EndsWith(".xlsx")) 
     { 
      strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", subfiles); 
     } 
     else if (subfiles.Trim().EndsWith(".xls")) 
     { 
      strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", subfiles); 
     } 

     OleDbConnection exlcon = new OleDbConnection(strConn); 
     exlcon.Open(); 
     string myTableName = exlcon.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString(); 

     OleDbDataAdapter oledbadpt = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), exlcon); 
     DataSet d_s = new DataSet(); 
     oledbadpt.Fill(d_s); 
     exlcon.Close(); 


     for (int i = 7; i < d_s.Tables[0].Rows.Count - 1; i++) 
     { 
      PARTNER_ID = d_s.Tables[0].Rows[i]["F1"].ToString(); 
      RTV_LOCTN = d_s.Tables[0].Rows[i]["F3"].ToString(); 

      DateTime date1 = Convert.ToDateTime(d_s.Tables[0].Rows[i]["F13"]); 
      string ddmm = date1.ToString("yyyyMMdd"); 
      string[] aa = Color_size.Split('/'); 
      // string colr=""; 
      string size = ""; 
      foreach (string ss in aa) 
      { 
       size = ss; 
      } 

      } 
      con.Open(); 
      SqlCommand myCommand = new SqlCommand(); 
      myCommand.Connection = con; 
      myCommand.Transaction = myTrans; 
      myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN)" + 
       " values('" + PARTNER_ID + "'," + "'" + RTV_LOCTN + "') "; 

      myCommand.ExecuteNonQuery(); 
      //con.Open(); 
      //SqlCommand cmdd = new SqlCommand(insert, con); 
      //int value1 = cmdd.ExecuteNonQuery(); 
      //values = string.Empty; 
      con.Close(); 


      if ((shrwcode != "") && (flag == "F")) 
      { 
       string zz = "select DistributionCenter,GLCountry,GLZone,GLState,GLCity from showroommaster where ShowroomCode='" + shrwcode + "'"; 
       SqlDataAdapter da11 = new SqlDataAdapter(zz, con); 
       DataSet ds11 = new DataSet(); 
       da11.Fill(ds11); 
       string Dcenter = ds11.Tables[0].Rows[0]["DistributionCenter"].ToString(); 
       string GLCountry = ds11.Tables[0].Rows[0]["GLCountry"].ToString(); 

       string fff = "select isnull(max(EntSrlNo),0)+1 as EntSrlNo from IDTableExtd where ShowroomCode='" + shrwcode + "' and DocDate='" + RTV_DATE + "'"; 
       SqlDataAdapter das = new SqlDataAdapter(fff, con); 
       DataSet dss = new DataSet(); 
       das.Fill(dss); 

       SqlCommand extdcmd = new SqlCommand(); 
       extdcmd.Connection = con; 
       extdcmd.Transaction = myTrans; 
       string docpre = "PR" + RTV_DATE.Substring(2, 2); 
       if (dss.Tables[0].Rows.Count > 0) 
       { 
        slno = Convert.ToInt32(dss.Tables[0].Rows[0]["EntSrlNo"].ToString()); 

        extdcmd.CommandText = "insert into IDTableExtd (ShowroomCode,TrnType,TrnCtrlNo,DocNoPrefix,docno,DocDate,EntSrlNo,StockNo,DistributionCenter,GLCountry,GLZone,GLState,GLCity,PartyType,PromoValue_LineLevel,DocQty,NetValue,BatchSrlNo)" + 
         "values ('" + shrwcode + "'," + "'2300'," + "'" + ddmm + "'," + "'" + docpre + "'," + "'" + ddmm + "'," + "'" + RTV_DATE + "'," + "'" + slno + "'," + "'" + TRN_STOCKNO + "'," + "'" + Dcenter + "'," + "'" + GLCountry + "'," + "'" + GLZone + "'," 
         + "'" + GLState + "'," + "'" + GLCity + "','10'," + '0' + ",'" + RTV_QTY + "'," + "'" + RTV_cost + "','0')"; 
        con.Open(); 
        // SqlCommand extdcmd = new SqlCommand(instableextd, con); 
        extdcmd.ExecuteNonQuery(); 
        con.Close(); 

       } 
      } 
     } 
     myTrans.Commit(); ///Error is getting after exceuting this line.. 
+1

아야 : "SQL 주입"- 그 검색하십시오 : 질문 (계속 읽기)하지만 관련이없는 (같이 : 해킹하지 않고 시스템을 파괴) 코드가 지금 대규모 안전하지 않습니다. 또한 : "''using 문 '/'IDisposable' –

+0

당신은 명백 할 수 있습니까? 그것이 던져주는'Commit' 라인 자체입니까? 또는 "after"something –

+0

내부 for 루프 내부에서 이미 열려있는 연결을 다시 열고 이전 연결에서 얻은 트랜잭션을 할당하려고 시도합니다. 이것이 올바르게 작동하는지 확신 할 수 없습니다. 그런데 왜 이미 열린 연결을 다시여십시오? – Steve

답변

0

먼저, your's 코드를 리팩토링, 그 같은 것을 사용해야합니다

using (var = new SqlConnection(_connectionstring)) 
{ 
    try 
    { 
     connection.Open(); 

     using(SqlTransaction transaction = connection.BeginTransaction()) 
     { 
      using (SqlCommand command1= new SqlCommand(commandtext, connection, transaction)) 
      { 
       //Do something here 
      } 
      using (SqlCommand command2= new SqlCommand(commandtext, connection, transaction)) 
      { 
       //Do another stuff here 
      } 
      ... 
      transaction .Commit(); 
     } 
    } 
    catch (Exception Ex) 
    { 
     if (transaction != null) transaction .Rollback(); 
    } 
} 
+0

예외를 삼켰습니다 ... –

0

(1) 요셉이 개체를 처리하는 데 도움이 Using 문을 사용하여 코드를 리팩토링 말했듯 정확히. SQL 주입하는 경향이

(2) 코드가

, 그래서 SQLParameter를 사용합니다.

코드의 샘플을 완전히 보여주었습니다.

con.Open(); 
      SqlCommand myCommand = new SqlCommand(); 
      myCommand.Connection = con; 
      myCommand.Transaction = myTrans; 
      myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN) values(@partnerId,@rtv)"; 
      myCommand.Parameters.Add(new SqlParameter("partnerId",PARTNER_ID)); 
      myCommand.Parameters.Add(new SqlParameter("rtv",RTV_LOCTN)); 
      myCommand.ExecuteNonQuery(); 
      //con.Open(); 
      //SqlCommand cmdd = new SqlCommand(insert, con); 
      //int value1 = cmdd.ExecuteNonQuery(); 
      //values = string.Empty; 
con.Close(); 
관련 문제