Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

java - Desktop application and DB connection

Lets say I have desktop application with simple login - here, in this part i have to create Connection, prepared statement which compares username and password. I use cardlayout- and for example, on another card (JPanel) i have JTable and JButton which retrieves values from SQL table to my JTable.... on third JPanel i have for example fields for name and password - using for new employee - he will give his name and password - after button click data will be inserted to DB

Now my Question: How does it work in real application? Shall I make one static method (e.g. getDBConnection()) which will create connection (first for login - after login close connection, then create another connection when i want to select from DB then close it and again if i want to insert something?) `

or how to do it in smarter/ proper way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can write a properties file specific to your application and write a class to load it.

MyDatabaseProperties.properties

database.jdbc.url = jdbc:mysql://localhost:3306/database
database.jdbc.driver = "com.mysql.jdbc.Driver"
database.jdbc.username = "USERNAME"
database.jdbc.password = "PASSWORD"

Properties.java:

public class Properties {
    private static final String PROPERTIES_FILE = "MyDatabaseProperties.properties";
    private static final Properties PROPERTIES = new Properties();

    static {
        try {
            PROPERTIES.load(new FileInputStream("MyDatabaseProperties.properties"));
        } catch (IOException e) {
            // THROW YOUR EXCEPTION HERE.
        }
    }
}

You will find an excellent material on this subject here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...