E
E
Evgeny Kolman2018-03-06 00:04:47
MySQL
Evgeny Kolman, 2018-03-06 00:04:47

Can't connect to database by URL?

I ran into a problem - I can not connect to the database by URL. Those. there is a servlet that connects to the database and makes a request. Having changed the URL to the real database and uploading the entire project to the server, I got an error connecting to the database.
I reproduced the problem by creating a new database on the locale with the name est, before that I used the database with the name fermer, in debugging I got the following picture: although I changed the URL, the program still tries to connect to the previous database.

spoiler

5a9db08b56bff061833617.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nubus4000, 2018-03-06
@Evgeny_13

Try like this. In the META-INF folder in the webapp, add context.xml with the content:

<?xml version="1.0" encoding="UTF-8"?>
<Context>

    <Resource name="jdbc/est"
              auth="Container"
              type="javax.sql.DataSource"
              maxActive="100" maxIdle="30" maxWait="10000"
              username="root"
              password="root"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost/est?useEncoding=true&amp;characterEncoding=UTF-8"/>
</Context>

After that, make a DaoUtil class and write this there (and it’s better to modify it, it is overloaded with all sorts of if, etc.):
public class DaoUtil {

    public static Connection getConnection(){
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            Context context = new InitialContext();
            Context initContext  = (Context )context.lookup("java:/comp/env");
            DataSource ds = (DataSource) initContext.lookup("jdbc/est");
            connection = ds.getConnection();
        }catch (SQLException | NamingException ex){
            ex.printStackTrace();
        }
        return connection;
    }

    public static void close(Statement statement, ResultSet rs,Connection connection){
        try {

            if (statement != null) {
                statement.close();
            }
            if (rs != null) {
                rs.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex){
            ex.printStackTrace();
        }
    }

}

Well, in the controller you can already write like this:
Well, it’s better to transfer work with connection and all sorts of statements to the Dao layer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question