Java J2ee Tutorials

MySQL Database Connection in Java

Monday, January 23, 2012

Description of program:

This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected from database".

Description of code:

Connection: This is an interface in java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver): This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that matches class with given string.

DriverManager: It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like:

url: - Database url where stored or created your database
userName: - User name of MySQL
password: -Password of MySQL

con.close(): This method is used for disconnecting the connection. It frees all the resources occupied by the database.

printStackTrace(): The method is used to show error messages. If the connection is not established then exception is thrown and print the message.

Code of program:

import java.sql.*;

public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Free Career Predictions

Delete Data Records Using JSP, My Sql

Saturday, January 14, 2012

deleteRecords.jsp

<%@ page language = "java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import = "java.sql.*"%>
Delete Records
<%! boolean success = false; %>
<%
int delID = Integer.parseInt(request.getParameter("deleteID"));
//String sql = "DELETE * FROM EMP_DETAIL WHERE ID = '"+delID+"'";
String sql = "DELETE FROM EMP_DETAIL WHERE ID = ?";

Connection con = null;
PreparedStatement psmt = null;
String url = "jdbc:mysql://localhost:3306/test_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, userName, password);
psmt = con.prepareStatement(sql);
psmt.setInt(1, delID);
int nRows = psmt.executeUpdate();
if(nRows == 0){
success = false;
}
else{
success = true;
}
psmt.close();
con.close();
%>
<%
if(success == true){
%>
One record deleted
View Records
<%
}
else{
%>

Can not delete record now. Please try later...
<%
}
%>

Free Career Predictions

Update Data Using JSP MySql

updateRecords.jsp


<%@ page language = "java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import = "java.sql.*"%>
<%@page import="java.util.*"%>
Update Records
<%! boolean success = false; %>
<%
int id = Integer.parseInt(request.getParameter("tid"));
int eid = Integer.parseInt(request.getParameter("employeeID"));
String empName = request.getParameter("employeeName");

String sql= "UPDATE EMP_DETAIL SET emp_id = '"+eid+"', emp_name = '"+empName+"' WHERE id = '" +id+ "'";

Connection con = null;
PreparedStatement psmt = null;
String url = "jdbc:mysql://localhost:3306/test_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url,userName,password);
psmt = con.prepareStatement(sql);
//psmt.setInt(2, eid);
//psmt.setString(3, empName);
int nRows = psmt.executeUpdate();

if(nRows == 0){
success = false;
}
else{
success = true;
}
psmt.close(); con.close();
%>
<%
if(success = true){
%>
Record updated
View Records
<%
}
else {
%>
Error - can not be updated
View Records
<%
}
%>

Free Career Predictions

Edit Records Using JSP MySql

editRecords.jsp

<%@ page language = "java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import = "java.sql.*"%>
<%@page import="java.util.*"%>
Edit Records
<%
int emp_id = Integer.parseInt(request.getParameter("editID"));

//String sql = "SELECT * FROM EMP_DETAIL WHERE ID= ? ";

Connection con = null;
PreparedStatement psmt = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test_db";
String userName = "root";
String password = "";
ResultSet rs = null;

try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, userName, password);
String sql = "SELECT * FROM EMP_DETAIL WHERE ID='"+emp_id+"'";
psmt = con.prepareStatement(sql);
rs = psmt.executeQuery();
while(rs.next()){
%>
<%
}
}
catch(Exception e){
out.println("Error: " +e);
}
con.close();
psmt.close();
%>
>Employee ID: >Employee Name:

Free Career Predictions

Retrieve Data Using JSP MySQL

viewRecords.jsp
<%@ page language = "java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import = "java.sql.*"%>
View Records
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/test_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";

%>
<%
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, userName, password);
String sql = "SELECT * FROM EMP_DETAIL ORDER BY EMP_ID ASC";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
//out.println(rs.getInt(1) +" : "+rs.getString(2) +"
");
int tID = rs.getInt(1);
int empID = rs.getInt(2);
String empName = rs.getString(3);
//out.print(" | ");
//out.println(rs.getString(2));
%>
<%
}
con.close();
//out.println("Data inserted");
%>
<%=empID%><%=empName%>Edit Delete

Free Career Predictions

Insert Record Using JSP MYSQL

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import = "java.sql.*"%>
Index
<%
int emp_id = Integer.parseInt(request.getParameter("employeeID"));
String str2 = request.getParameter("employeeName");
String str_email = request.getParameter("employeeEmail");
Connection con = null;
PreparedStatement psmt = null;
String url = "jdbc:mysql://localhost:3306/test_db";
String driver = "com.mysql.jdbc.Driver";
//String dbName = "test_db";
String userName = "root";
String password = "";
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, userName, password);
//con = DriverManager.getConnection(url+dbName, userName, password);
String sql = "INSERT INTO EMP_DETAIL(emp_id, emp_name, emp_email) VALUES (?, ?, ?)";
psmt = con.prepareStatement(sql);
psmt.setInt(1, emp_id);
psmt.setString(2, str2);
psmt.setString(3, str_email);
psmt.executeUpdate();
out.println("Thank you: Record inserted.");
}
catch (Exception e){
out.println("Error: "+e);
}
finally {
psmt.close();
con.close();
}
%>

Free Career Predictions

Create ID

createId.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Create Employee ID
Employee ID:
Employee Name:
Employee Email ID:

Free Career Predictions