2014-10-20 3 views
0

연결이 닫힌 경우에도 mysql이 스크립트를 실행할 수 있습니까? .NET 커넥터 API를 통해 mysql 커뮤니티 서버를 사용하고 있습니다. API를 테스트하기 위해 C#을 사용하고있었습니다.연결이 닫힌 경우에도 MySqlScript를 실행하는 MySQL

나는 다음과 같은 정적 클래스를 가지고

using System; 
using System.Data; 

using MySql.Data; 
using MySql.Data.MySqlClient; 

public static class DataBase 
{ 
    static string connStr = "server=localhost;user=root;port=3306;password=*******;"; 
    static MySqlConnection conn; 

    public static bool Connect() 
    {   
     conn = new MySqlConnection(connStr); 
     try 
     {    
      conn.Open();    
     } 
     catch (Exception Ex) 
     { 
      ErrorHandler(Ex); 
      return false; 
     } 
     return true; 
    } 
    public static int ExecuteScript(string scripttext) // returns the number of statements executed 
    { 
     MySqlCommand cmd = conn.CreateCommand(); 
     cmd.CommandText = scripttext; 
     MySqlScript script; 
     int count= 0; 

     try 
     { 
      script = new MySqlScript(conn, cmd.CommandText); 

      script.Error += new MySqlScriptErrorEventHandler(script_Error); 
      script.ScriptCompleted += new EventHandler(script_ScriptCompleted); 
      script.StatementExecuted += new MySqlStatementExecutedEventHandler(script_StatementExecuted); 
      count = script.Execute(); 
     } 
     catch (Exception Ex) 
     { 
      count = -1; 
      ErrorHandler(Ex);    
     } 
     return count; 
    } 

    # region EventHandlers 
    static void script_StatementExecuted(object sender, MySqlScriptEventArgs args) 
    { 
     string Message = "script_StatementExecuted"; 
    } 

    static void script_ScriptCompleted(object sender, EventArgs e) 
    { 
     string Message = "script_ScriptCompleted!"; 
    } 

    static void script_Error(Object sender, MySqlScriptErrorEventArgs args) 
    { 
     string Message = "script_Error: " + args.Exception.ToString(); 
    } 
    # endregion 
    public static bool Disconnect() 
    { 
     try 
     { 
      conn.Close(); 
     } 
     catch (Exception Ex) 
     { 
      ErrorHandler(Ex); 
      return false; 
     } 
     return true; 
    } 
    public static void ErrorHandler(Exception Ex) 
    { 
     Console.WriteLine(Ex.Source); 
     Console.WriteLine(Ex.Message); 
     Console.WriteLine(Ex.ToString()); 
    } 

} 

와 나는 비록 내가 끊기를 (사용하여 내 MySQL의 연결을 종료 한 것으로 나타났습니다

using System; 
using System.Data; 
namespace Sample 
{ 
    public class Sample 
    { 
     public static void Main() 
     { 
      if (DataBase.Connect() == true) 
       Console.WriteLine("Connected"); 

      if (DataBase.Disconnect() == true) 
       Console.WriteLine("Disconnected"); 

      int count = DataBase.ExecuteScript("drop database sample"); 
      if (count != -1) 
      { 
       Console.WriteLine(" Sample Script Executed"); 
       Console.WriteLine(count); 
      } 

      Console.ReadKey(); 

     } 


    } 
} 

이 클래스를 테스트하려면 다음 코드를 사용하고) - 내가 정의한, mysql은 다음에주는 명령을 실행하고 오류가 발생하지 않는다.

닫힌 연결에서 스크립트를 실행하려고 할 때 오류가 발생해야하므로 내가 잘못 생각한 것처럼 느껴집니다.

내 코드/논리 또는 mysql 커넥터의 결함에 문제가 있습니까?

mysql 워크 벤치를 통해 명령이 제대로 실행되었는지 여부를 확인했습니다. 이 MySqlScript.Execute 코드의 컴파일입니다

+0

'novice' 코드를 리팩터링하고 연결 코드를'using() {}'블록 주위에 감싸고 연결이 여전히 있는지 확인하기 위해 조건부 검사를 추가 할 수도 있습니다 공개 여부 .. – MethodMan

+0

나는 그것을 정확히 할 예정이었다. 이것은 커넥터 API가 제대로 작동하는지 확인하는 샘플 코드 일뿐입니다. 감사합니다. – novice

답변

2

....

public unsafe int Execute() 
{ 

    ...... 

    flag = 0; 
    if (this.connection != null) 
    { 
     goto Label_0015; 
    } 
    throw new InvalidOperationException(Resources.ConnectionNotSet); 
Label_0015: 
    if (this.query == null) 
    { 
     goto Label_002A; 
    } 
    if (this.query.Length != null) 
    { 
     goto Label_002C; 
    } 
Label_002A: 
    return 0; 
Label_002C: 
    if (this.connection.State == 1) 
    { 
     goto Label_0047; 
    } 
    flag = 1; 
    this.connection.Open(); 
    .... 

당신이 MySqlScript에게 내부 변수와 스크립트를 실행하기 전에 저장되고 전달 된 연결을 빌드 할 때 경우에 당신이 볼 수 있듯이 내부 연결 변수가 닫히고 코드가이를 엽니 다. 체크하지 않았지만 종료하기 전에 연결을 닫았다 고 가정합니다 (열기 전에 플래그 = 1을 확인하십시오).

이 부분은 글로벌 MySqlConnection 객체를 유지하지 않도록 코드를 변경하는 것이 좋습니다. 추적 할 수없는 매우 어려운 버그가 발생할 위험이 없습니다.

static string connStr = "server=localhost;user=root;port=3306;password=*******;"; 

public static MySqlConnection Connect() 
{   
    MySqlConnection conn = new MySqlConnection(connStr); 
    conn.Open();    
    return conn; 
} 

이 방법은

public static int ExecuteScript(string scripttext) // returns the number of statements executed 
{ 
    using(MySqlConnection conn = Database.Connect()) 
    using(MySqlCommand cmd = conn.CreateCommand()) 
    { 
     cmd.CommandText = scripttext; 
     .... 
    } 
} 

하기 닫기 귀중한 자원을 자유롭게 연결하고 명령을 처리 할 것이다 문을 사용하여 또한 예외의 경우에 당신은 확실 할 것이다 using 문을 사용하는 코드를 작성 할 수 있습니다 연결을 닫고 처리하게하려면

+0

그래서 Execute는 닫혀있는 경우 연결을 엽니 다? 어떤 기능을 제공 할 것입니다 .. 나는 스크립트가 실행되기 전에 연결이 열려 있는지 확인합니다. 적어도 잘못해서는 안된다. – novice

+0

DataAdapter 코드에서 채택한 것과 동일한 기능입니다. MSDN의 [SqlDataAdapter.Fill]에 대한 문서 (http://msdn.microsoft.com/en-us/library/zxkb3c3d (v = vs.110) .aspx) 비고 절 참조 – Steve

+0

Thanks a lot Steve – novice

관련 문제