How to connect MySql Database Using JSP


Jul 24, 2011    Janaki Mahapatra, JAVA

1. Create a database "sample" in your mysql. If you are using windows version of mysql then right click on schema tab as the following picture. [caption id="attachment_189" align="alignnone" width="300" caption="create database or schema in mysql"][/caption] 2.  Copy the mySqlConnector.jar in lib directory of your project. 3. Copy the following code to your jsp file.
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
String dbms="mysql";
String serverName="localhost";
String portNumber="3306";
String userName="root";
String password="root";
String databaseName="sample";

String connectionURL = "jdbc:"+ dbms +"://"+ serverName +":"
+ portNumber +"/"+databaseName;
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, userName, password);

if(!connection.isClosed()){
out.println("Successfully connected to " + "MySQL server using TCP/IP...");
connection.close();
}
else{
	out.println("Unable to connect to database.");
}

%>