i newbie in Java.
I want create small application, which connect to MySQL and execute some queries.
My real problem - connect to mysql, and keep this connection for other classes, without opening connection again and again.
I read documentation about MVC and OOP. But i still can't understand how i can resolve this problem.
As i imagine, i should inherit a database class in models, like user and messages from mypackage. But i don't imagine how it should looks.
I already tried search some examples in google, but i found only simple example with one main class and database class.
So, i need someone, who can explain it for me
I will be grateful for any help
User class
package mypackage;
class user {
public String getName() {
// return value from mysql
}
}
Messages class
package mypackage;
class messages {
public String getMessage() {
// return value from mysql
}
}
Database class
package database;
class db {
private String dbUri = "jdbc:mysql://";
private String dbDriver = "com.mysql.jdbc.Driver";
private Connection connection;
public boolean connect(String host, String base, String user, String pass)
{
try {
Class.forName(dbDriver);
String uri = dbUri + host + '/' + base;
connection = DriverManager.getConnection(uri, user, pass);
return true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
// Could not find the database driver
} catch (SQLException e) {
e.printStackTrace();
return false;
// Could not connect to the database
}
}
}
Main class
import mypackage.*;
import database.*;
class main
{
public static void main(String[] args)
{
database db = new database();
user usr = new user();
System.out.println(usr.getName());
messages msg = new messages();
System.out.println(msg.getMessage());
}
}