N
N
NoMoneyException2016-12-10 22:51:23
Java
NoMoneyException, 2016-12-10 22:51:23

What is a good practice for working with DB in Java?

Hello. please advise how to properly organize work with the database in a small java application. There is an idea to create a class something like this:

class DataBase{
//пару статических переменных (логин пасс и т.д.)
//в конструкторе инициализируем и открываем соединение

//функция execute которая будет принимать SQL-код и перенеправлять его на statement.execute(...)
//функция close() которая будет вызвана в конце работы программы
}

Is this approach correct? If yes, then please tell me how to correctly place the variables inside the class (for example, the same statement, how to declare it correctly? in try with resources, then you won’t get access from other functions, but otherwise you will have to check if it is empty)
And if not , then advise how to do it like a human. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2016-12-10
@leahch

1) use the connection pool
2) try to collect all the sql rows in several places, for example, in factory classes. In the same factories, give out ready-made pojo classes
3) try to use prepared statements everywhere
4) working with transactions is a separate thing, I recommend using threadlocal to store transactions
Study spring and its DI, read - https://docs.spring.io/ spring/docs/current/spring-...
Well, try to learn hibernate!!!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question