banner



How To Install Mysql Connector Java In Windows

MySQL Java Connector

Java Connector

MySQL provides connectivity for Java client applications with MySQL Connector/J, a driver that implements the Java Database Connectivity (JDBC) API. The API is the manufacture standard for database-independent connectivity between the Java programming language and a wide range of – SQL databases, spreadsheets etc. The JDBC API can do the post-obit things :

  • Constitute a connection with a database or access any tabular data source.
  • Transport SQL statements.
  • Retrieve and procedure the results received from the database.

In the post-obit section, we have discussed how to install, configure, and develop database applications using MySQL Connector/J (JDBC driver).

MySQL Connector/J version :

Connector/J
version
JDBC
version
MySQL Server
version
Status
5.1 3.0, four.0 4.1, 5.0, 5.1, 5.v, five.6, 5.7 Recommended version
5.0 3.0 4.i, five.0 Released version
3.i three.0 4.1, 5.0 Obsolete
3.0 3.0 3.x, four.1 Obsolete

Download Connector/J :
MySQL Connector/J is the official JDBC driver for MySQL. You tin can download the latest version of MySQL Connector/J  binary or source distribution from the following web site -
http://dev.MySQL.com/downloads/connector/j/

For Platform Independent select any one from the following :

mysql java connector (platform independent) download

For Microsoft Windows :

mysql java connector (windows) download

Installation

You can install the Connector/J package drivers using either the binary, binary installation or source installation. The binary method is piece of cake which is a package of necessary libraries and other files pre-built, with an installer program. The source installation method is of import where you want to customize or modifies the installation process or for those platforms where a binary installation package is not bachelor. Apart from that solution, yous manually add the Connector/J location to your Java classpath.
MySQL Connector/J is distributed as a .cypher or .tar.gz archive containing the sources, the class files. Later on extracting the distribution archive, you tin can install the driver by placing MySQL-connector-java-version-bin.jar in your classpath, either by calculation the total path to it to your classpath environment variable or by directly specifying information technology with the control line switch -cp when starting the JVM.
Y'all tin can set up the classpath surround variable under Unix, Linux or Mac Os Ten either locally for a user within their .profile, .login or some other login file. Yous can too set it globally by editing the global /etc/profile file.
For example add the Connector/J driver to your classpath using ane of the following forms, depending on your command trounce :

# Bourne-uniform trounce (sh, ksh, bash, zsh): shell> export CLASSPATH=/path/MySQL-connector-coffee-ver-bin.jar:$CLASSPATH  # C crush(csh, tcsh): shell> setenv CLASSPATH /path/MySQL-connector-coffee-ver-bin.jar:$CLASSPATH        

In Windows 2000, Windows XP, Windows Server 2003 and Windows Vista, you can set the environment variable through the System Control Panel.

Install Java Connector on Microsoft Windows

Select and download the MSI installer packages from http://dev.MySQL.com/downloads/connector/j/ every bit per your requirement.

Now follow the following steps :

Step -one :
Double click the installer (here information technology is "MySQL-connector-java-gpl-5.1.31.msi")

mysql jdbc install step1

Step -ii :
Click on 'Run' and complete the procedure.

mysql jdbc install step2

Connecting to MySQL using MySQL Connector/J

The following example shows how to connect/terminate and handle errors. (Java version seven Update 25 (build 1.7.0_25-b16))

          import coffee.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;    public class test    {        public static void principal (Cord[] args)        {            Organisation.out.println("\northward\n***** MySQL JDBC Connectedness Testing *****"); 		   Connection conn = naught;            try            { 		   Class.forName ("com.MySQL.jdbc.Driver").newInstance ();                String userName = "root";                String password = "pqrs123";                Cord url = "jdbc:MySQL://localhost/sakila";                        conn = DriverManager.getConnection (url, userName, password);                System.out.println ("\nDatabase Connection Established...");            }           grab (Exception ex)            { 		       System.err.println ("Cannot connect to database server"); 			   ex.printStackTrace();            }       		    		   finally            {                if (conn != zip)                {                    effort                    {                        Arrangement.out.println("\n***** Permit terminate the Connection *****"); 					   conn.close ();					                           System.out.println ("\nDatabase connectedness terminated...");                    }                    catch (Exception ex) 				   { 				   Organization.out.println ("Error in connection termination!"); 				   }                }            }        }    }                  

Caption:

To create a coffee jdbc connection to the database, y'all must import the following java.sql bundle.

  • import java.sql.Connection;
  • import java.sql.DriverManager;
  • import coffee.sql.SQLException;

At present nosotros volition brand a class named 'test' so the main method.

To create a connection to a database, the code is :

conn = DriverManager.getConnection (url, userName, countersign);

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is the backbone of the JDBC compages. The DriverManager has a method called getConnection(). The method uses a jdbc url, username and a countersign to establish a connexion to the database and returns a connection object. Nosotros have used the following url, username and password in the above code.

  • The url cord is "jdbc:MySQL://localhost/sakila" where the starting time part "jdbc:MySQL://localhost" is the database blazon (here it is MySQL) and server (here it is localhost). Rest part is the database proper name (here it is 'sakila').
  • The user name for MySQL is defined inside the variable 'userName'.
  • The password for MySQL is defined within the variable 'password'.

The DriverManager attempts to connect to the database, if the connection is successful, a Connection object is created, (hither information technology is called 'conn') and the programme volition display a message "Database Connexion Established..."

If the connection fails (e.g. supplying wong password, host accost etc.) and so you lot demand to handle the situation. We are trapping the error in catch office of the try … catch statement with appropriate messages and finally shut the connexion.

Compile and Run information technology

Presume that 'test.java' is stored in E:\ and 'MySQL-connector-java-5.1.31-bin.jar' is stored in "C:\Program Files\MySQL\MySQL Connector J\".

mysql jdbc execution

Notation : The class path is the path that the Java Runtime Surroundings (JRE) searches for classes and other resource files. You can change the class path by using the -classpath or -cp selection of some Java commands when you call the JVM or other JDK tools or past using the classpath environs variable.

Querying information using MySQL Connector/J

Suppose we want to become the names (first_name, last_name), bacon of the employees who earn more than the average salary and who works in any of the IT departments.

Structure of 'hr' database :

mysql data model

Sample table : employees

SQL Lawmaking :

          SELECT first_name, last_name, salary  FROM employees  WHERE department_id IN  (SELECT department_id FROM departments WHERE department_name LIKE 'IT%')  AND salary > (SELECT avg(salary) FROM employees);                  

Here is the Java Code (version 7 Update 25 (build one.vii.0_25-b16))

          import java.sql.Connexion; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Argument; import java.sql.ResultSet;    public class testsql    {        public static void chief (String[] args)        {            Connection conn = zilch;            try            { 		   Form.forName ("com.MySQL.jdbc.Driver").newInstance ();                String userName = "root";                Cord password = "datasoft123";                String url = "jdbc:MySQL://localhost/60 minutes";                        conn = DriverManager.getConnection (url, userName, password);   // Run SQL -> start from here			                Statement stmt = null;             ResultSet rs = null;              try {               stmt = conn.createStatement();               rs = stmt.executeQuery("SELECT first_name, last_name, salary FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE department_name Like 'IT%') AND salary > (SELECT avg(salary) FROM employees)"); // Extract data from effect fix              System.out.println ("\n-------------SQL Information-------------\n");              while(rs.next()){              //Retrieve by column name        		 String fname = rs.getString("first_name");              String lname = rs.getString("last_name"); 		    int salary = rs.getInt("Salary");             //Display values             System.out.impress("Name " + fname+' '+lname);             Organisation.out.print(",Salary: " + bacon);             } 			 Organisation.out.println ("\n\n-------------END-------------\n");           }           catch (SQLException ex){          // handle any errors            System.out.println("SQLException: " + ex.getMessage());            System.out.println("SQLState: " + ex.getSQLState());            System.out.println("VendorError: " + ex.getErrorCode());            }          finally {            if (rs != null) {             try {             rs.close();         } catch (SQLException sqlEx) { } // ignore          rs = null;            }           if (stmt != null) {             try {             stmt.shut();            } catch (SQLException sqlEx) { } // ignore              stmt = nix;          }            }			    // SQL stop at hither			               }     catch (Exception ex)         { 	      Organisation.err.println ("Cannot connect to database server"); 	      ex.printStackTrace();         }       		        finally         {           if (conn != null)           {            try            { ///System.out.println("\due north***** Permit stop the Connection *****"); 		   conn.close ();					              // System.out.println ("\n\nDatabase connexion terminated...");             }           catch (Exception ex) 	        { 		    Arrangement.out.println ("Mistake in connection termination!");     		 }             }           }        }    }                  

Compile and Run it

Assume that 'testsql.coffee' is stored in E:\ and 'MySQL-connector-java-5.one.31-bin.jar' is stored in "C:\Plan Files\MySQL\MySQL Connector J\".

mysql jdbc sql output

Note : The form path is the path that the Java Runtime Environment (JRE) searches for classes and other resource files. Y'all can change the form path by using the -classpath or -cp option of some Java commands when you lot call the JVM or other JDK tools or by using the classpath environment variable.

Previous: MySQL Python Connector
Next: MySQL Storage Engines (table types)

Source: https://www.w3resource.com/mysql/mysql-java-connection.php

Posted by: queeneruscoulk.blogspot.com

0 Response to "How To Install Mysql Connector Java In Windows"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel