title: Java. Share MySQL connection between classes
body: <p>i newbie in Java.</p>
  
  <p>I want create small application, which connect to MySQL and execute some queries.</p>
  
  <p>My real problem - connect to mysql, and keep this connection for other classes, without opening connection again and again.</p>
  
  <p>I read documentation about MVC and OOP. But i still can't understand how i can resolve this problem.</p>
  
  <p>As i imagine, i should inherit a database class in models, like <code>user</code> and <code>messages</code> from <code>mypackage</code>. But i don't imagine how it should looks.</p>
  
  <p>I already tried search some examples in google, but i found only simple example with one main class and database class. </p>
  
  <p>So, i need someone, who can explain it for me</p>
  
  <p>I will be grateful for any help</p>
  
  <p>User class</p>
  
  <pre><code>package mypackage;
  class user {
      public String getName() {
          // return value from mysql
      }
  }
  </code></pre>
  
  <p>Messages class</p>
  
  <pre><code>package mypackage;
  class messages {
      public String getMessage() {
          // return value from mysql
      }
  }
  </code></pre>
  
  <p>Database class</p>
  
  <pre><code>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
          }
      }
  }
  </code></pre>
  
  <p>Main class</p>
  
  <pre><code>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());
      }
  }
  </code></pre>