Programming
 
MySQL with JAVA
 
The Java Installation
 
To develop your own Java programs you need the Java Software Development Kit (Java SDK, or simply JDK). The most widely distributed JDK is from Sun (the creator of Java); however, there are Java implementations available from other developers, such as IBM. This chapter focuses primarily on the Sun implementation.
 
JDK is bundled with many Linux implementations and can be simply installed with the package manager. For Linux distributions without Java, or for working under Windows, you can download the JDK without charge from java.sun.com/downloads (about 40 megabytes). The official name is Java 2Platform Standard Edition n SDK (or J2SE n SDK) for short), where n is the current version number.
 
I would suggest you to use the latest JDK and Connector/J. Check the Connector/J documentation for compatibility information. After installation you have to complete the environment variable PATH to the bin directory of the Java installation. To do this, modify the file autoexec.bat under Windows 9x/ME. Under Windows NT/2000/XP, System Properties-->Advanced-->Environment Variables and append the Java's bin path to the existing path.
 
 
Installation
 
Connector/J is available for download at http://www.mysql.com/products/connector/j/ as a *.zip (Windows) or *.tar.gz file. Both Archives contain exactly the same files. (Java is platform-independent.) To install, unpack the contents of the archive into the directory of your choice. Under Windows, use the program Winzip, and under Linux the following command:
 
linux:~ # tar -xzf mysql-connector-java-n.tar.gz
 
Here is a list of the most important files and directories of the archive:
 
mysql-connector-java-n/
 
Directory with the actual library files; the rest of the entries in this list refer to this directory.
 

mysql-connector-java-n/

Directory with the actual library files; the rest of the entries in this list refer to this directory.

README

The documentation to Connector/J.

/mysql-connector-java-n.jar

All Java Classes of the driver as a Java archive file; this file is the actual driver.

/com/*

All Java classes of the driver as individual files.

/org/*

The driver's Java start class under the old driver name (org.gjt.mm.mysql.Driver).

 
The crucial point here is that the Java runtime environment should be able to find the new library when executing programs. To ensure this state of affairs, there are several possibilities:
 
. The simplest solution is generally to copy the file mysql-connector-java-n.jar into the directory java-installation-directory\jre\lib\ext, which is automatically checked during the execution of Java programs.
 
. Alternatively, you can set the environment variable CLASSPATH. This variable specifies all directories in which there are classes that should be taken into account when Java programs are executed. So that Connector/J will be considered, you must add the directory in which mysql-connector-java-n.jar is located to CLASSPATH. Note that for the execution of Java programs from the current directory, CLASSPATH must also contain the path "." (that is, a period, which denotes the current directory).
 
Under Windows, you can set CLASSPATH temporarily with the DOS command SET var=xxx. To set it permanently, use the dialog CONTROL PANEL |SYSTEM under Windows NT/2000/XP, or under Windows 9x/ME, the file autoexec.bat.Components of CLASSPATH are separated by semicolons.
 
Under Linux, you can set CLASSPATH with the command export var=xxx or permanently in /etc/profile. The specified directories in Classpath are separated with colons.
 
. For initial testing there is also the option of copying the com and org directories from Connector/J into the local directory (that is, into the directory in which the program that you have developed resides). Availability
 
You can test whether the installation of Connector/J was successful with the following mini program.
 
Loading the Driver:
 
Class.forName("com.mysql.jdbc.Driver").newInstance();
 
Establishing connection with MySQL database:
 
con=java.sql.DriverManager.getConnection
("jdbc:mysql://localhost:3306/sampleDB",uid,password);
 
It should run without reporting any errors:
 
/**
*@author: xyz < xyz@ebizel.com >
*@description: program to check MySQL
Connector/J installation and
MySQL database connectivity from java program
*
*/

public class  Check_MySQL
{
	/**
	*@description: Variabale declration
	*/
static  java.io.PrintStream out=java.lang.System.out;
java.sql.Connection con=null;
static java.lang.String uid="root",password="sa";

	public Check_MySQL()
	{
		try
		{
			out.println("+-----------------------+");
			out.println("+------------------------+");
			out.println("+------------------------+");
			/**
			MySQL Driver instance
			*/
 
 
 
Class.forName("com.mysql.jdbc.Dri ver").newInstance();
			Thread.sleep(500);
			out.println("+-------------------------+");
			out.println("+--------------------------+");
			out.println("+--------------------------+");
			out.println("+--------------------------+");
			out.println("+--------------------------+");
			con=java.sql.DriverManager.getConnection
("jdbc:mysql://localhost:3306/sampleDB",uid,password);
			Thread.sleep(300);
			out.println("+--------------------------+");
			out.println("+----------------------------+");

		}
		catch (Exception e)
		{

			out.println("+--------------------------+");
			out.println("+---------------------------+");
		}
		finally
		{
			try
			{
				if (con!=null)
				{
					con.close();
 
 
 
{
				if (con!=null)
				{
					con.close();
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}

		}
	}
	public static void main(String[] args)
	{

		Check_MySQL cmy=new Check_MySQL();
	}
}
 
 
 
And If It Doesn't Work?
 
If something goes wrong, then the usual suspect is that the Connector/J classes have not been found. The error message usually looks something like this: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. Here are some of the possible sources of error:
 
. If you have copied mysql-connector-java-3.0.n.jar into the directory jre\lib\ext, then it is possible that more than one Java interpreter resides on the computer. (It is also possible that a run-time version and a development version have been installed in parallel.) You have apparently copied mysql-connector-java-3.0.n.jar into the directory of an interpreter that is not the active one.
 
Under Linux you can determine the correct directory easily with which java. Unfortunately, there is not a comparable option under Windows, since the relevant settings are located in the somewhat opaque registration database. However, you can determine with START |SETTINGS |CONTROL PANEL |ADD/REMOVE HARDWARE which Java versions are already installed and when installation took place.
 
. If you have edited CLASSPATH, then perhaps Java is having no trouble locating Connector/J's classes, but is unable to locate the classes of your own program (error message java.lang.NoClassDefFoundError). If CLASSPATH is defined, then it must also point to the current directory.
 
Under Windows, you can determine the contents of CLASSPATH in a command window with %CLASSPATH%, and under Linux in a console window with $CLASSPATH. Under Windows, the components of CLASSPATH are separated with semicolons, while under Linux it is colons that do the separation. The following commands show possible settings (where of course, you must adapt the configuration to your own installation):
 
> ECHO %CLASSPATH%
 
 
linux:~ # echo $CLASSPATH
 
.:/usr/local/mysql-connector-java-3.0.3-beta/
 
or add mysql-connector-java-n-bin.jar to the existing classpath ender system environment variable.
 
 
here n is the version number of the mysql connector/J such as version 5.0.5.
 
Alternatively you can try running your program with the following command :
 
java -classpath
.;mysql_connector_J_path\mysql-connector-java-5.0.5-bin.jar Check_MySQL
 
now it should display the following output:
 
 
Example:

The sample program given below demonstrates how you retrieve data into your Java application from a MySQL table. Sample below shows how you can perform custom actions depending upon the query results.
 
Source code for login.sql
 
create database sampledb;
use database sampledb;
create table login
(
uid varchar(20) not null,
password varchar(15) not null,
email varchar (75),
Primary Key (uid)
);
 
 
Source code for Login.java :
 
import javax.swing.*;
/**
*
*@author: xyz.#xyz@ebizel.com
*
*/
public class Login extends javax.swing.JFrame
{
	/**
	*Variable declaration
	*/
	private javax.swing.JLabel l1,l2,l3;
	private javax.swing.JTextField uidFld;
	private javax.swing.JPasswordField pass;
	private javax.swing.JButton
         loginB,resetB,forgotB,abtB,signupB;
	private static java.sql.Connection con;
	private java.sql.ResultSet rs;
	private java.sql.PreparedStatement pst;
	private javax.swing.JPanel p1;
	static	java.io.PrintStream
        out=java.lang.System.out;

	 /**
	 *Connection details
	 */
	static String  db="sampledb",
         dbUser="root",dbPass="sa",
         dbURL="jdbc:mysql://localhost",
         dbDriver="com.mysql.jdbc.Driver";
 
 
 
static int dbPort=3306;
	public Login()
	{
		super("eBIZ Login Manager");
		javax.swing.JFrame.setDefaultLook
                 AndFeelDecorated(true);
 		try
		{
		Class.forName(Login.dbDriver).newInstance();
		Thread.sleep(500);

	out.println("+----------------------------+");
	out.println("+----------------------------+");
	out.println("+----------------------------+");
	out.println("+----------------------------+");
	out.println("+----------------------------+");

	con=java.sql.DriverManager.
        getConnection
       (dbURL+":"+String.valueOf(dbPort)
        +"/"+db,dbUser,dbPass);

			Thread.sleep(300);

		}
		catch (Exception e)
		{
			out.println(e);
		}

		initComp();
		this.setResizable(false);
		this.setDefaultCloseOperation
(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
		this.setSize(310,210);
		this.show(true);
		this.setLocation(100,200);
		this.addWindowListener(new java.awt.event.WindowAdapter()
		{
			public void windowClosing(java.awt.event.WindowEvent we)
			{
 
 
 
int
r=javax.swing.JOptionPane.showConfirmDialog
(new javax.swing.JFrame(),"Are you sure
you want to exit Login manager [Y/N]","eBIZ Login
Manager",javax.swing.JOptionPane.YES_NO_OPTION); if (r==javax.swing.JOptionPane.YES_OPTION) System.exit(0); else return; } } ); } private void initComp() { javax.swing.JFrame.setDefaultLookAndFeelDecorated(true); p1=new javax.swing.JPanel (); getContentPane().add(p1); p1.setLayout(null); l1=new javax.swing.JLabel
("Welcome to eBIZ Login Manager"); l1.setBounds(10,2,230,25); p1.add(l1); l2=new javax.swing.JLabel("User ID"); l2.setBounds(5,35,100,25); p1.add(l2); uidFld=new javax.swing.JTextField(); uidFld.setBounds(110,35,120,20); p1.add(uidFld); l3=new javax.swing.JLabel("Password"); l3.setBounds(5,61,100,25); p1.add(l3); pass=new javax.swing.JPasswordField(); pass.setBounds(110,61,100,20); p1.add(pass);
 
 
 
loginB=new javax.swing.JButton("Login");
loginB.setBounds(3,90,80,25);
loginB.setCursor
(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); p1.add(loginB); loginB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent ae) { int result=doLogin(uidFld.getText(),pass.getText()); if (result==1) javax.swing.JOptionPane.showMessageDialog
(new javax.swing.JFrame(),
"Login Sucess","eBIZ Login Manager",
javax.swing.JOptionPane.INFORMATION_MESSAGE); else javax.swing.JOptionPane.showMessageDialog
(new javax.swing.JFrame(),
"Login Failed","eBIZ Login Manager",
javax.swing.JOptionPane.ERROR_MESSAGE); } } ); resetB=new javax.swing.JButton("Reset"); resetB.setBounds(84,90,80,25); p1.add(resetB); resetB.addActionListener
(new java.awt.event.ActionListener() { public void actionPerformed
(java.awt.event.ActionEvent ae) { uidFld.setText(""); pass.setText(""); } } );
 
 
	forgotB=new javax.swing.JButton("Forget Password");
forgotB.setBounds(165,90,140,25);
p1.add(forgotB);

abtB=new javax.swing.JButton("About");
abtB.setBounds(3,115,80,25);
p1.add(abtB);

abtB.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent ae)
{
showAbout();
	}
	}
);

signupB=new javax.swing.JButton("Register for new User ID");
signupB.setBounds(84,115,221,25);
p1.add(signupB);


}
public int doLogin(String id,String pass)
{
final String id1=id,pass1=pass;
int result=0;
try
{
Class.forName(Login.dbDriver).newInstance();
con=java.sql.DriverManager.getConnection
(dbURL+":"+String.valueOf(dbPort)+"/"+db,dbUser,dbPass); pst=con.prepareStatement
("select * from login where uid=? and password=?"); pst.setString(1,id); pst.setString(2,pass); rs=pst.executeQuery(); if (rs.next()) { result= 1;
 
 
 
	}
			else
				result=0;

			return result;
		}
		catch (Exception e)
		{
			out.println(e);return 0;
		}

	}
private void showAbout()
	{
javax.swing.JOptionPane.showMessageDialog(this,"
eBIZ Login Manager
Developed by : xyzi","About Login Manager",
javax.swing.JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] args) { javax.swing.JFrame.setDefaultLookAndFeelDecorated(true); Login l=new Login(); } }