简体   繁体   中英

Database access class best practices

Im creating a simple DBHelper for my postgre DB using a JDBC driver.

Im wondering what are the best practices?

For example, are methods like initConnection() closeConnection() or any other, should be static one? Like:

void foo{
    DBHelper.initConnection();
    // do some logic, maybe:
    // Data someData = DBHelper.getSomeData();
    DBHelper.closeConnection();
}

Or maybe better if i will create a DBHelper object and call method for object. Like:

void foo2{
    DBHelper dbhelper = new DBHelper();
    dbhelper.initConnection();
    // do some logic, maybe:
    // Data someData = dbhelper.getSomeData();
    dbhelper.closeConnection();
}

Is it matter at all?

Do i need always check if connection is open before i will try to retrive some data? What if it is close? And always try to close it in finally block?

EDIT: in answer to @Kayaman comment:

So my foo method like this?

 void foo3{
    Connection conn = DBHelper.getConnection();
    // do some logic, maybe:
    // Statement statement = conn.createStatement();
    // some stmt work
    conn.close() //do i need check if stmt is closed before? 
}

That will make my DBHelper class usefull only to getting connection. There will be no logic inside? (like GetInterestingRecords() or GetRecordsWithId(30) ?

您是否考虑过在服务器配置文件(如果是Web应用程序)中定义连接属性,并且在整个应用程序生命周期中都打开了会话?

Before implementing DBHelper you should check if some java libraries may satisfy your needs. If you take a look at this there are listed some libraries that seem to fit your problem.

If you decide to go on with your own custom implementation I suggest to make DBHelper a normal class with no static methods for managing the connections; the main reason is that with static methods you cannot manage multiple (ie connections to different databases) db connections at the same time. If you are using a java 7 implementation in your onw library you could also implement tha AutoClosable inferface in order to better manage the resource you library is managing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM