Database connection with custom java class

Post here your questions about SFS2X. Here we discuss all server-side matters. For client API questions see the dedicated forums.

Moderators: Lapo, Bax

moonlife
Posts: 45
Joined: 26 Sep 2016, 08:22

Database connection with custom java class

Postby moonlife » 07 Apr 2021, 12:56

Hi,

Is it possible to reach SFSDBManager from any native java class.

Detailed example is below

Code: Select all

public class DbConnect
{
    public DbConnect() {
   
      Connection conn;
      PreparedStatement stmt;
      public String SomeMethod() {
         String res = "";
         try {
            
            sql = "SELECT * FROM table";
                conn = getParentZone().getDBManager().getConnection();
                stmt = conn.prepareStatement(sql);
               
                ResultSet resultSet = stmt.executeQuery();
         }
         catch (SQLException) {
            
         }
         finally{
             if (stmt != null)
                        stmt.close();
               
                if (conn != null)
                        conn.close();
         }
         return res;
      }
   }
}
User avatar
Lapo
Site Admin
Posts: 23008
Joined: 21 Mar 2005, 09:50
Location: Italy

Re: Database connection with custom java class

Postby Lapo » 07 Apr 2021, 13:41

Yes,
each Zone has its own DBManager, if you have activated it from the config.

So you can get a reference to your current Zone and from there access the DBManager.
Example:

Code: Select all

Zone zone = SmartFoxServer.getInstance().getZoneManager().getZoneByName("myZone");
IDBManager dbMan = zone.getDBManager();
...


You can also skip the first line if you simply pass a reference of your zone from the Extension calling the class.

Cheers
Lapo
--
gotoAndPlay()
...addicted to flash games
moonlife
Posts: 45
Joined: 26 Sep 2016, 08:22

Re: Database connection with custom java class

Postby moonlife » 07 Apr 2021, 14:48

Thanks,

I tried but I got error like as follow,

Cannot get a connection, pool error: Pool exhausted
User avatar
Lapo
Site Admin
Posts: 23008
Joined: 21 Mar 2005, 09:50
Location: Italy

Re: Database connection with custom java class

Postby Lapo » 07 Apr 2021, 16:11

Can you elaborate a little bit better?
Did the error appear immediately? Or after some time?

Also, you need to configure the database connection pool according to the load you expect. If your application runs hundreds of DB queries per second you might need a larger connection pool and also set the policy to "GROW" so that it can be expanded with higher load.

Let us know
Lapo

--

gotoAndPlay()

...addicted to flash games

Return to “SFS2X Questions”

Who is online

Users browsing this forum: No registered users and 69 guests