文章 "如何从 MQL5 (MQL4) 访问 MySQL 数据库" - 页 2

 
Can you provide the source code of your EA/Script?
 
elugovoy:
Can you provide the source code of your EA/Script?

MQL CODE is collect mt4 data to the mysql table,  when use in one mt4 in only one, it is ok, when use four or more in two mt4, it print Access violation read to 0x00000002 in ..\MQLMySQL.dll'

 


附加的文件:

senddata.mq4 11 kb

the sendata.mq4 is my uploaded EA source code. 

 
elugovoy:
Can you provide the source code of your EA/Script?
//+------------------------------------------------------------------+
//|                                                        数据库操作.mq4 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict


input string Host = "localhost"; //喊单服务器IP,如192.168.1.210, localhost
input string User = "root";  //mysql数据库登录用户名
input string Password = "root"; //mysql数据库登录密码
input string Database = "test";  //mysql数据库名
input string Socket = "0"; // database credentials
input int Port = 3306; //mysql数据库端口号
input int ClientFlag = 0;

int DB = 0; // database identifier//---
int timeSeconds = 1; //定时器
#include <MQLMySQL.mqh>

string Query;

int i,Cursor,Rows;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
 {

 }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
      
       if( IsExpertEnabled() && IsConnected() && AccountNumber() > 0 )
       {
           
           int account = AccountNumber();
                                
           string symbol = Symbol();     
           
           //int syDB = 0; // database identifier//---
           
           DB = cMySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); 
                
           //Alert(DB);
           
           double spread = (Ask - Bid); 
           
           //Alert(symbol);
           
           Query = "SELECT * FROM " + symbol + " where AccountNumber = " + (string)AccountNumber();
           //Print(Query);
           Cursor = MySqlCursorOpen(DB, Query);
             
           
           if (Cursor >= 0)
           {
                 Rows = MySqlCursorRows(Cursor);
                 
                 int dataRows = Rows; 
                 //Alert(dataRows);
                 
                 if( dataRows > 0 )
                 {
                       Query = "update " + symbol + " set Bid = "+(string)Bid + ", Ask = " + (string)Ask
                       + ", Spread = " + DoubleToStr(spread, Digits)  
                       + ", Time = '" + TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS) +"' where AccountNumber = " 
                       + (string)account; // + "' and Symbol = '" + symbol +"'";
                       
                       MySqlExecute(DB, Query);
                        
                 }
                 else if( dataRows == 0 )
                 {
                      
                      Query = "CREATE TABLE IF NOT EXISTS " + symbol + " (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AccountNumber int, "
                      + "Symbol char(20), Bid double, Ask double, Spread double," 
                      + "Memo char(50), " 
                      + "Time datetime)ENGINE=MEMORY DEFAULT CHARSET=utf8 "; 
                      
                      MySqlExecute(DB, Query);
                      
                      Query = "INSERT INTO " + symbol + "(AccountNumber, Symbol, Bid, Ask, Spread, Memo, Time) VALUES (" 
                      + (string)account + ", '" + symbol + "', "+(string)Bid+","+ (string)Ask + "," 
                      + DoubleToStr(spread, Digits) 
                      + ", '" + (string)AccountCompany()
                      +"', \'"+TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS)+"\')";
                      
                      if(MySqlExecute(DB, Query) != true )
                      {
                           //Query = "DROP TABLE IF EXISTS `data_table`";
                           //MySqlExecute(DB, Query);
                           Query = "CREATE TABLE IF NOT EXISTS " + symbol + "(id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AccountNumber int, "
                            + "Symbol char(20), Bid double, Ask double, Spread double," 
                            + "Memo char(50), " 
                            + "Time datetime)ENGINE=MEMORY DEFAULT CHARSET=utf8 "; 
                            
                           MySqlExecute(DB, Query);
                      }
                     
                 }                
                 
                 MySqlCursorClose(Cursor); // NEVER FORGET TO CLOSE CURSOR !!!
            }
            
        }
      
}
//+------------------------------------------------------------------+

 

I used three DB connect, but I used the same DB, is it need to create new  DB for any new database CRUD?


自动交易和策略测试
自动交易和策略测试
  • www.mql5.com
MQL5:MetaTrader 5客户端内置的交易策略语言。语言允许编写您自己的自动交易系统,技术指标,脚本和函数程序库
 

Ok, I see you have wrote an expert advisor for this purposes, and it is written without recommendations I've posted in article.

So, let's move step by step:

1.  The calling of " DB = cMySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); " should be made inside OnInit() standard function instead of OnTick().

2.  You are uses cMySqlConnect - it's imported function form DLL, you have to use MySqlConnect function instead of cMySqlConnect function !

3. You have to call MySqlDisconnect function inside OnDeinit() stundard function.

4. You have to check database connection identifier inside OnTick() standard function to be sure that connect was successful.

 

Finally it will looks like:

... your code
int DB = -1; // database identifier//---
... your code
int OnInit()
{
   DB = MySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); 

   if (DB != -1)
    {
    // connection succeeded!
    // here you have to define table creation logic
   }
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
 {
 MySqlDisconnect(DB);
 }

void OnTick()
{
 // first command:
 if (DB==-1) return; // do not any action when no connection

 // here your code without cMySqlConnect call
}
You have to rebuild your code based on the requirements of project, as I see the currently there is no clear logic, everything messed up.
 
elugovoy:

Ok, I see you have wrote an expert advisor for this purposes, and it is written without recommendations I've posted in article.

So, let's move step by step:

1.  The calling of " DB = cMySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); " should be made inside OnInit() standard function instead of OnTick().

2.  You are uses cMySqlConnect - it's imported function form DLL, you have to use MySqlConnect function instead of cMySqlConnect function !

3. You have to call MySqlDisconnect function inside OnDeinit() stundard function.

4. You have to check database connection identifier inside OnTick() standard function to be sure that connect was successful.

 

Finally it will looks like:

Thanks, I'll try again and give the result back.
 
elugovoy:

Ok, I see you have wrote an expert advisor for this purposes, and it is written without recommendations I've posted in article.

So, let's move step by step:

1.  The calling of " DB = cMySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); " should be made inside OnInit() standard function instead of OnTick().

2.  You are uses cMySqlConnect - it's imported function form DLL, you have to use MySqlConnect function instead of cMySqlConnect function !

3. You have to call MySqlDisconnect function inside OnDeinit() stundard function.

4. You have to check database connection identifier inside OnTick() standard function to be sure that connect was successful.

 

Finally it will looks like:

I changed step by step, but the problem is still exist when use the expert in one mt4 for four or more symbols. it print " Access violation read to 0x0000000B in '...MQLMySQL.dll'
"

the code is followed

<--


#include <MQLMySQL.mqh>

 

int    MySqlErrorNumber;       // recent MySQL error number

string MySqlErrorDescription;  // error description


//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

{

       EventSetTimer(timeSeconds);

       

       DB = MySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); 

       if( DB == -1 )

       {

            Print("Database is not connected ... ");

       }

       

       return(INIT_SUCCEEDED);

}

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

{

      MySqlDisconnect(DB); 

      EventKillTimer();

      ObjectsDeleteAll();

}


void OnTimer()

{

      //Alert(TimeCurrent());

      OnTick();

}


//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

 {

       if( DB == -1 )

       {

            Alert("Database is not connected ... ");

            return;

       }

        

       if( IsExpertEnabled() && IsConnected() && AccountNumber() > 0 && DB != -1 )

       {

           

           int account = AccountNumber();

                                

           string symbol = Symbol();

           if( cmd != "" && cmd != NULL )

           {

               symbol = cmd;

           }

           

           symbolOrder = symbol + "_table";   

           

           double spread = (Ask - Bid);

           

           admission = spread*MathPow(10, Digits); 

           

           //int DB = cMySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); 

           

           Query = "SELECT * FROM " + symbol + " where AccountNumber = " + (string)AccountNumber();

           //Print(Query);

           int Cursor1 = MySqlCursorOpen(DB, Query);

           

           if (Cursor1 >= 0)

           {

                 int Rows1 = MySqlCursorRows(Cursor1);

                 

                 int dataRows1 = Rows1; 

                 //Alert(dataRows);

                 

                 if( dataRows1 > 0 )

                 {

                       Query = "update " + symbol + " set Bid = "+(string)Bid + ", Ask = " + (string)Ask

                       + ", Spread = " + DoubleToStr(spread, Digits)  

                       + ", Time = '" + TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS) +"' where AccountNumber = " 

                       + (string)account; // + "' and Symbol = '" + symbol +"'";

                       

                       MySqlExecute(DB, Query);

                       

                       MySqlCursorClose(Cursor1);

                       

                 }

                 else if( dataRows1 == 0 )

                 {

                      

                      Query = "CREATE TABLE IF NOT EXISTS " + symbol + " (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AccountNumber int, "

                      + "Symbol char(20), Bid double, Ask double, Spread double," 

                      + "Memo char(50), " 

                      + "Time datetime)ENGINE=MEMORY DEFAULT CHARSET=utf8 "; 

                      

                      MySqlExecute(DB, Query);

                      

                      Query = "INSERT INTO " + symbol + "(AccountNumber, Symbol, Bid, Ask, Spread, Memo, Time) VALUES (" 

                      + (string)account + ", '" + symbol + "', "+(string)Bid+","+ (string)Ask + "," 

                      + DoubleToStr(spread, Digits) 

                      + ", '" + (string)AccountCompany()

                      +"', \'"+TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS)+"\')";

                      

                      if(MySqlExecute(DB, Query) != true )

                      {

                           //Query = "DROP TABLE IF EXISTS `data_table`";

                           //MySqlExecute(DB, Query);

                           Query = "CREATE TABLE IF NOT EXISTS " + symbol + "(id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AccountNumber int, "

                            + "Symbol char(20), Bid double, Ask double, Spread double," 

                            + "Memo char(50), " 

                            + "Time datetime)ENGINE=MEMORY DEFAULT CHARSET=utf8 "; 

                            

                           MySqlExecute(DB, Query);

                      }

                     

                 }                

                 

                 MySqlCursorClose(Cursor1); // NEVER FORGET TO CLOSE CURSOR !!!

            }

           

       }

             

      

       

       

 

--> 

 
elugovoy:

Ok, I see you have wrote an expert advisor for this purposes, and it is written without recommendations I've posted in article.

So, let's move step by step:

1.  The calling of " DB = cMySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); " should be made inside OnInit() standard function instead of OnTick().

2.  You are uses cMySqlConnect - it's imported function form DLL, you have to use MySqlConnect function instead of cMySqlConnect function !

3. You have to call MySqlDisconnect function inside OnDeinit() stundard function.

4. You have to check database connection identifier inside OnTick() standard function to be sure that connect was successful.

 

Finally it will looks like:

The problem is it can't use in one mt4 for more than two symbols, if use in only one symbol, it's normal. When use in four or more, it's run fine, but after a few minutes, it prints the problem"Access violation read to 0x0000000B in '...MQLMySQL.dll'"

The exambles is all scripts, it's run only one times, You may try one experts call the dll in four or more symbols in one or two mt4, You may find the problem.

Would be the dll needs a memeoy release or garbe collection? 

 
MFC dumps leaks prematurely whenit exits, instead of waiting for the   
CRT to dump leaks following static data destruction, and this causes   
spurious leak reports for objects which allocated memory before MFC   
was initialized and which thus are destroyed after MFC exits. This is   
commonly observed when using the MFC DLL in a program that also uses   
the C++ runtime DLL.
 

Hello once again.

Based on the code you have provided I guess you are new to MQL.

I'm sorry, I have no time to teach you, but I have time for testing the software I've developed.

So, here are logs attached. I have running 2 accounts within 6 and 5 charts concurrently.

Have build testing EA for you, based on your logic: each table defined for each currency pair and can keep the online market data for different accounts.

You can inspect the logs, no one error "Access violation..." was raised.

The problem is not in MQLMySQL library.

Testing EA:

//+------------------------------------------------------------------+
//|                                                       DFTest.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property strict
#include <MQLMySQL.mqh>

input string Host = "localhost";
input string User = "root";
input string Password = "ioctrl";
input string Database = "mysql";
input int Port = 3306;
input string Socket = "";
input int ClientFlag = 0;

input int Timer = 1; // Timer (seconds) not used now

int DB;

int OnInit()
{
 SQLTrace = true; // to see all the queries would be send to the database
       EventSetTimer(Timer);
       DB = MySqlConnect(Host, User, Password, Database, Port, Socket, ClientFlag); 
       if( DB == -1 )
       {
            Print("Database is not connected! Error: ", MySqlErrorDescription);
            return (INIT_FAILED);
       }
       
 // create table if not exists
 string cmd;
 cmd = "CREATE TABLE IF NOT EXISTS `" + Symbol() + "` (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AccountNumber int, "
       + "Symbol char(20), Bid double, Ask double, Spread double, " 
       + "Memo char(50), " 
       + "Time datetime) ENGINE=MEMORY DEFAULT CHARSET=utf8";
 if (!MySqlExecute(DB, cmd))
    {
     Print ("Table creation error: ",MySqlErrorDescription);
     return (INIT_FAILED);
    }
                      

       return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
      MySqlDisconnect(DB); 
      EventKillTimer();
}


void OnTimer()
{
 // you should never call OnTick from OnTimer and vice versa.
 // the target of these 2 functions is different
}

void OnTick()
{
 int account;
 string symbol;
 double spread;
 string Query, cmd;
 int Cursor;
 int Rows;
 
 if (DB == -1)
    {
    Comment("Database is not connected ... ");
    return;
    }

 if ( IsExpertEnabled() && IsConnected() && AccountNumber() > 0 )
    {
     account = AccountNumber();
     symbol = "`"+Symbol()+"`"; // if you have to use it as table name you have to use quotes as a good practice for MySQL database
     
 
 spread = (Ask - Bid);
 
 // possible it could be better to use something like this: admission = MarketInfo(symbol, MODE_SPREAD);
 Query = "SELECT * FROM " + symbol + " where AccountNumber = " + (string)account;
 Cursor = MySqlCursorOpen(DB, Query);
 if (Cursor >= 0)
    {
      Rows = MySqlCursorRows(Cursor);
      if ( Rows > 0 )
         {
          cmd = "update " + symbol + " set Bid = "+(string)Bid + ", Ask = " + (string)Ask
                       + ", Spread = " + DoubleToStr(spread, Digits)  
                       + ", Time = '" + TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS) +"' where AccountNumber = " + (string)account;
         }
      else
         {
          cmd = "INSERT INTO " + symbol + "(AccountNumber, Symbol, Bid, Ask, Spread, Memo, Time) VALUES (" 
                + (string)account + ", \'" + symbol + "\', "+DoubleToStr(Bid,Digits)+","+ DoubleToStr(Ask,Digits) + ","  + DoubleToStr(spread, Digits) 
                + ", \'" + AccountCompany() +"\', \'"+TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS)+"\')";
         }
      if (!MySqlExecute(DB, cmd))
         {
          Print("Updating error: ",MySqlErrorDescription);
          Print (cmd);
         }

      MySqlCursorClose(Cursor);
     }
  }

} 

 

 This is right logic of using the library.

Due to optimization you can even do not use SELECT statement, just execute UPDATE statement , than check if (MySqlRowsAffected()==0) means no one row was updated and needs INSERT, so apply the INSERT statement.

You have ~100% of updates, so this workaround can increase the performance and reduce network traffik.

And at the end, full source codes of project (include DLL development) has been attached to the article, you may change it on your own way.

If you fill that the problem in MqlMySQL.DLL anyway, you can debug it and fix for yourself.

 

Best wishes, 

Eugene 

附加的文件:
logs.zip  302 kb
 

how are you !

system win10 64x, Unable to connect to the database ,can you help me ?


原因: