Java J2ee Tutorials

Showing posts with label Java MySQL Connection. Show all posts
Showing posts with label Java MySQL Connection. Show all posts

mysql-connector.jar for Connecting Java to MySQL

Tuesday, February 7, 2012

This blog helps one how to connect java to mysql database, there are some steps to follow at first check for the java if java is not installed download latest jdk from sun java, This is where you can get latest java development kit http://java.sun.com/javase/downloads/index.jsp be sure that you installed java, you can check that via command prompt or terminal use this command without quote “java -version” so you must see like this java version “1.6.0_16″, Basically java has no jar file or pre built class for mysql connection which is called mysql-connector i mean driver class which supports for mysql connection so its better to download package called mysql connector so this plays a major role during connection so download that from a mysql web site http://www.mysql.com/products/connector/ they given more version look for latest version and download ans place it in a know place say(c:\mysql or /home/mysql) but don’t forget to unzip mysql-connector and i believe that mysql-server service already started in system.

This is program check the connectivity of mysql-server through localhost

import java.sql.*;

public class DatabaseConnectionExample {
public static void main(String args[]) {
System.out.println("Database Connection Example");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
//String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName(driver).newInstance();
//con = DriverManager.getConnection(url + dbName,userName,password);
con = DriverManager.getConnection(url,userName,password);
System.out.println("Database Connected");
con.close();
System.out.println("Connection Colsed.");
}
catch (Exception e){
System.out.println("Error: "+e);
}
}
}

Save as DatabaseConnectionExample.java, while compile it you have to include classpath of java to know more about classpath sun java is best guide http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/classpath.html

Now it time to compile open command prompt go to the location of DatabaseConnectionExample.java if your your program is under c:\

use c: also may be at /home for tux users now compile it using javac -classpath /home/mysql/mysql-connector.bin.jar DatabaseConnectionExample.java so this command has three part javac, -calsspath, filepath, here javac is a compiler and we included a classpath of mysql-connector jar file locate that wherever it is for an example i given as /home/mysql/mysql-connector.bin.jar and next to that is java file. after compilation program needs to run so java interpreter shall do this job if this command is used java -classpath /home/mysql/mysql-connector.bin.jar: DatabaseConnectionExample. in my second I used colon so its specific for linux user unless windows use ;(semi-colon)

For Eclipse users, use can import mysql-connector.jar file to classpath before creating a class file, right click the project go to properties and choose java build path and then choose libraries tab and add external jar file.

Program shows this output
Database Connected.
Connection Closed.

Free Career Predictions

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

Insert Record Using JSP MYSQL

Saturday, January 14, 2012

<%@ 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