Vous êtes sur la page 1sur 4

In java we have been provided with some classes and APIs with which we can make use of the

database as we like. Database plays as very important role in the programming because we have to store the values somewhere in the back- end.

Connecting to a MySQL Database in Java


In java we have been provided with some classes and APIs with which we can make use of the database as we like. Database plays as very important role in the programming because we have to store the values somewhere in the back- end. So, we should know how we can manipulate the data in the database with the help of java, instead of going to database for a manipulation. We have many database provided like Oracle, MySQL etc. We are using MySQL for developing this application. In this section, you will learn how to connect the MySQL database with the Java file. Firstly, we need to establish a connection between MySQL and Java files with the help of MySQL driver. Now we will make our account in MySQL database so that we can get connected to the database. After establishing a connection we can access or retrieve data form MySQL database. We are going to make a program on connecting to a MySQL database, after going through this program you will be able to establish a connection on your own PC. 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 display 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. Driver Manager: 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. Here is the 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(); } } }

Java Utilities Package


The java.util package has a number of utility classes Vector class Stack class Dictionary class Hashtable class Properties class Random class create array-like objects that can grow and shrink dynamically offers conventional stack operations push and pop along with several others gives us the framework for storing keyed data in tables and retrieving the data a technique for rapidly storing and retrieving information from tables a collection of rendom number capabilities

enables us to create persistent hash tables i.e hashtables that can be written and read from

Vector Class and Enumeration Before I begin, the Enumeration interface has been superceded by the Iterator interface in more recent version of Java, but there is still alot of code in the wild that still uses the Enumeration interface, so I will explain how to use it here. I have also discussed various collection methods in object collections, so take a peek to see all the options you have available. Java arrays are fixed in size, they cannot grow or shrink, thus the Vector class offers an arraylike structure that can dynamically grow in response to an applications changing storage requirements. Vectors have capacity which is the space that has been reserved for the array, if a Vector needs to grow, it grows by an increment that you specify or by the default assumed by the system. If you do not specify a capacity increment, the system will automatically double the size of the Vector each time additional capacity is needed. Vectors can store objects, thus a reference to an object of any class type can be stored in a Vector. Stack Class There is not point in reinventing the wheel, I have already discussed how to implement a stack but Java offers a Stack class which extends Vector to implement a stack data structure. Like Vector a Stack can store objects, thus a reference to an object of any class type can be stored in a Stack. Dictionary Class A dictionary maps keys to values, A key is supplied and the dictionary returns a value. Dictionary is an abstract class and is the superclass of the hashtable class. Each key in the

dictionary is unique, the data structure is simular to a dictionary of words and definitions, the word is the key and the definition is the value. Hashtable Class I have already explained hashing in object collections, Java offers the Hashtable class, one problem with hashing is when collisions occur (two different keys in the same cell (or element)), since we cannot store two different records in the same space, we need to find an alternative home for all records beyond the first that hash to a particular array subscript. There are many schema's for doing this, one way is to hash again, another scheme uses one hash to locate the first first candidate cell, if that cell is occupied, successive cells are search linearly until an available cell is found. The most popular solution is to have each cell of the table be a hash bucket typically a linked list of all key/value pairs that hash to that cell. This is the solution that the hashtable class offers. One factor that affects performance of hashing schemes is called the load factor, this is the ratio of the number of occupied cells in the hash table to the size of the hash table. The closer this ratio gets to 1.0 the greater the change of collisions. Increase load factor Decrease load factor Properties Class A properties Object is a persistent Hashtable, by persistent we to that the Hashtable is written to a file, then read back. In fact most objects in Java can now be output and input with Java's serialization. Random Class Java provides extensive additional random number generation capabilities in class Random. The repeatablility of random numbers that occurs when the seed value is used is useful for testing and debugging, however when in a production evnironment you used remove the seed value. Random example Random with seed value example Random r = new Random(); Random rsv = new Random( <seed value> ); rsv.setSeed( <new seed value> ); ## resets the seed value

By increaing the load factor we get better memory utilization, but the program runs slower due collisions.

By decreasing the load factor we get better program speed because of reduced hashing collisio memory utilization because a larger portion of the hash remains empty.

Vous aimerez peut-être aussi