Tuesday, July 25, 2006

Connecting Java Server Pages (JSP) with MySQL

If we learn a new software technology, of course we want to know how the software connected to the database. In this article, i'll explain how Java Server Pages (JSP) connected with MySQL.

For a note :

(1) If you installed Apache-Tomcat Web Server, the default directory for JSP are in "/webapps/examples/jsp". It can be different for any version of Apache-Tomcat depending of your Apache-Tomcat version.


(2) If you want to use your own .class, make a new .class and put on "/webapps/examples/WEB-INF/classes/your_class_name". If that directory doesn't exist please fill free to create a new one. Only your .class file is needed.

To connect with MySQL, you need mysql-connector-java. You can download it from MySQL official site. Copy "mysql-connector-java-3.0.8-stable-bin.jar" to "$JAVA_HOME/jre/lib/ext" and then restart your Apache-Tomcat web server.

Below is an example script how JSP get a data from MySQL database.

<%@ page import="java.sql.*" %>
<%
String connectionURL = "jdbc:mysql://localhost:3306/pudak2?user=;password=";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
%>
<html>
<body>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL,"","");
statement = connection.createStatement();
rs = statement.executeQuery("SELECT * FROM t_admin");
while (rs.next()) {
out.println (rs.getString("adm_code")+"<br/>");
}
rs.close();
%>
</body>
</html>


That's all. In the next article, i'll explain how to interact Apache-Tomcat with Apache-HTTP server, so Apache-Tomcat can use port 80. Happy learning Java Server Pages.

1 comment:

shasthika said...

perfect explanation about java programming .its very useful.thanks for your valuable information.java training in chennai | java training in velachery