0

I'm trying to learn java and how to use it for web applications . I'm already familiar with PHP so i'm trying to learn how to use JSP since it seems to be the closest thing to PHP in Java. My school provides us with a fre MySQL v5.1 databases so I'm using that as my db. When connecting to a database in PHP I use mysqli and do

$mysqli = new mysqli("oniddb.cws.oregonstate.edu", "username, "pword", "username");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} 

For Java and JDBC I'm having a hard time finding the equivalent to this. Everything I've found implies my database is local and not over the web. How can I do this in JSP?

Thanks in advance

user2466886
  • 205
  • 1
  • 3
  • 14
  • How does your code look like? Do you get any specific error/exception? Do you know port on which what DB allows you to connect? Have you seen: http://stackoverflow.com/questions/2121829/com-mysql-jdbc-exceptions-jdbc4-communicationsexceptioncommunications-link-fail? – Pshemo May 30 '16 at 17:08

1 Answers1

1

Сonnecting to a database directly from JSP is possible, but it is a bad practice.

JSP is designed to be a view, but not a place where "back-end" logic happens. Ideally, it should just use parameters that are passed from a backend.

If I were you I would start with learning JDBC (API for connecting to databases from Java). Here is a tutorial from Oracle

And after learning JDBC you can apply you knowledge in web using MVC pattern for example.

  • Thanks I'll look at the tutorial. I've looked at JDBC documentation before and the reason I'm confused is that in order to connect to a database I need the server name and the port number which implies that the db is local. In this case the db is not local, I only have access to it via my username and password and the db url that is provided by my school. Can you point me to documentation that will connect to a web url? – user2466886 May 30 '16 at 18:16
  • It's absolutely not a problem. Just connect with the URL you used, but change "localhost" to the IP address of the server and check that the port is correct. This link might be helpful: http://stackoverflow.com/questions/2318250/how-to-connent-to-a-remote-mysql-database-with-java – Ivan Nikolaychuk May 31 '16 at 05:16