How to keep a connection alive

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vieraci
    New Member
    • Mar 2008
    • 4

    How to keep a connection alive

    Hi,

    I'm wanting to start a database connection at the start of an app and keep it open for all methods and classes that I'm #including in my project.

    First I went about it by creating the connection in the Main source file outside of any class declarations and then declaring it external in other source files.

    Code:
    // Main cpp file 
    #include <mysql++>
    
    mysql::Connection * conn;
    
    // Class definitions follow, I open the connection in Main()
    if (!(conn.connect("dbName", "localhost", "user", "pwd"))) {
    ...
    This works ok within the same source file and although it compiles, the connection is not open in any function defined outside the file (in another source file).

    Second method I tried was to pass the mysql::Connecti on * conn as a parameter: // Call MyFn from a method in Main source file:
    MyFn(this, &conn);

    connection appears alive but but the app crashes when I execute the query:

    Code:
    // Function def in Another source file
    void myFn(wxFrame *frame, Connection *conn)
    {
       mysqlpp::Query query = conn.query();  <--- THIS is probably the cause !?
    // set up query code...
    // execute
       mysqlpp::StoreQueryResult res = query.store();  // <--- Exception happens here
    Can anyone help me please ?
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    Use the pconnect, if that exists in your class.

    Ronald

    Comment

    • vieraci
      New Member
      • Mar 2008
      • 4

      #3
      Originally posted by ronverdonk
      Use the pconnect, if that exists in your class.

      Ronald
      I don't find any reference to pconnection anywhere. Is it a MySQL object ?

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        You will have to look in your programming language reference for the function to open a 'persistent connection'. Like in PHP it is command mysql_pconnect(), as opposed to command mysql_connect().

        Ronald

        Comment

        • chaarmann
          Recognized Expert Contributor
          • Nov 2007
          • 785

          #5
          You can use a connection-pool.

          A connection pool is a thread (or process) that keeps a list of all connections. It has functions for con=pool.borrow Coonnection() and pool.returnConn ection(con) .
          It uses a periodic cleanup-function to go through all connections inside the list and closes the ones which are not used for a certain time.

          Comment

          • vieraci
            New Member
            • Mar 2008
            • 4

            #6
            Thanks, I'll read up on the connection pools

            Comment

            Working...