19321927-MySQL-and-Java
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
1,764
On Slideshare
1,764
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
28
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Data types of MySQL and Java programming language are not same, its need some mechanism for transferring databetween an database using MySQL data types and a application using Java data types. We need to provide Javamappings for the common MySQL data types. We have to confirm that we have proper type information then onlywe can correctly store and retrieve parameters and recover results from MySQL statements.There is no particular reason that the Java data type needs to be exactly isomorphic to the MySQL data type. Forexample, Java String dont precisely match any of the MySQL data CHAR type, but it gives enough type informationto represent CHAR, VARCHAR or LONGVARCHAR successfully.The following table represent the default Java mapping for various common MySQL data types: MySQL Type Java TypeCHAR StringVARCHAR StringLONGVARCHAR StringNUMERIC java.math.BigDecimalDECIMAL java.math.BigDecimalBIT booleanTINYINT byteSMALLINT shortINTEGER intBIGINT longREAL floatFLOAT doubleDOUBLE doubleBINARY byte []VARBINARY byte []LONGVARBINARY byte []DATE java.sql.DateTIME java.sql.TimeTIMESTAMP java.sql.Tiimestamp 1. CHAR, VARCHAR and LONGVARCHAR MySQL data types CHAR, VARCHAR, LONGVARCHAR are closely related. CHAR represents a small, fixed-length character string, VARCHAR represents a small, variable-length character string, and LONGVARCHAR represents a large, variable-length character string. There is no need for Java programmer to distinguish these three MySQL data types. These can be expressed identically in Java. These data types could be mapped in Java to either String or char[]. But String seemed more appropriate type for normal use. Java String class provide a method to convert a String into char[] and a constructor for converting a char[] into a String. The method ResultSet.getString allocates and returns a new String. It is suitable for retrieving data from CHAR, VARCHAR and LONGVARCHAR fields. This is suitable for retrieving normal data, but LONGVARCHAR MySQL type can be used to store multi-megabyte strings. So that Java programmers needs a way to retrieve the LONGVARCHAR value in chunks. To handle this situation, ResultSet interface have two methods for allowing programmers to retrieve a LONGVARCHAR value as a Java input stream from which they can subsequently read data in whatever size chunks they prefer. These methods are getAsciiStream and getCharacterStream, which deliver the data stored in a LONGVARCHAR column as a
  • 2. stream of ASCII or Unicode characters.2. NUMERIC and DECIMAL The NUMERIC and DECIMAL MySQL data types are very similar. They both represent fixed point numbers where absolute precision is required. The most convenient Java mapping for these MySQL data type is java.math.BigDecimal. This Java type provides math operations to allow BigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimal types, with integer types, and with floating point types. We also allow access to these MySQL types as simple Strings and char []. Thus, the Java programmers can use the getString() to retrieve the NUMERICAL and DECIMAL results.3. BINARY, VARBINARY and LONGVARBINARY These MySQL data types are closely related. BINARY represents a small, fixed-length binary value, VARBINARY represents a small, variable-length binary value and LONGVARBINARY represents a large, variable-length binary value. For Java programers there is no need to distinguish among these data types and they can all be expressed identically as byte arrays in Java. It is possible to read and write SQL statements correctly without knowing the exact BINARY data type. The ResultSet.getBytes method is used for retrieving the DECIMAL and NUMERICAL values. Same as LONGVARCHAR type, LONGVARBINARY type can also be used to return multi-megabyte data values then the method getBinaryStream is recommended.4. BIT The MySQL type BIT represents a single bit value that can be zero or one. And this MySQL type can be mapped directly to the Java boolean type.5. TINYINT, SMALLINT, INTEGER and BIGINT The MySQL TINYINT type represents an 8-bit integer value between 0 and 255 that may be signed or unsigned. SMALLINT type represents a 16-bit signed integer value between -32768 and 32767. INTEGER type represents a 32-bit signed integer value between -2147483648 and 2147483647. BIGINT type represents an 64-bit signed integer value between -9223372036854775808 and 9223372036854775807. These MySQL TINYINT, SMALLINT, INTEGER, and BIGINT types can be mapped to Javas byte, short, int and long data types respectively.6. REAL, FLOAT and DOUBLE The MySQL REAL represents a "single precision" floating point number that supports seven digits of mantissa and the FLOAT and DOUBLE type represents a "double precision" floating point number that supports 15 digits of mantissa. The recommended Java mapping for REAL type to Java float and FLOAT, DOUBLE type to Java double.7. DATE, TIME and TIMESTAMP These three MySQL types are related to time. The DATE type represents a date consisting of day, month, and year, the TIME type represents a time consisting of hours, minutes, and seconds and the TIMESTAMP type represents DATE plus TIME plus a nanosecond field. The standard Java class java.util.Date that provides date and time information but does not match any of these three MySQL date/time types exactly, because it has DATE and TIME information but no nanoseconds. Thats why we define three subclasses of java.util.Date. These are: •
  • 3. java.sql.Date for SQL DATE information. • java.sql.Time for SQL TIME information. • java.sql.Timestamp for SQL TIMESTAMP information.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 theback- end. So, we should know how we can manipulate the data in the database with the help of java, instead ofgoing to database for a manipulation. We have many database provided like Oracle, MySQL etc. We are usingMySQL 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 aconnection between MySQL and Java files with the help of MySQL driver . Now we will make our account inMySQL database so that we can get connected to the database. After establishing a connection we can access orretrieve data form MySQL database. We are going to make a program on connecting to a MySQL database, aftergoing 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 ofAPIs interfaces and methods. If connection is established then it shows "Connected to the database" otherwise it willdisplays 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) afterthat 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 MySQLcon.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 themessage.Here is the code of program:import java.sql.*;
  • 4. 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(); } }}After establishing the connection with MySQL database by using the JDBC driver, you will learn how we can createour database. A database is a large collection of data or information stored in our computer in an arranged way. Ithelps us for accessing, managing and updating the data easily. In this example we are going to create a database byMySQL and with the help of some java methods and SQL statement. A RDBMS (Relational Database ManagementSystem) is a type of DBMS (Database Management System) which stores the data in the form of tables. So, we canview and use the same database in many different ways.Description of program:Firstly this program establishes the connection with MySQL database and takes a database name as its input in thedatabase query and only after that it will create a new database and show a message "1 row(s) affected" otherwise, itdisplays "SQL statement is not executed!".Description of code:CREATE DATABASE db_name;Above code is used for creating a new database. It takes a database name and then a new database is created by thatname.Here is the code of program:import java.io.*;import java.sql.*;public class CreateDatabase{ public static void main(String[] args) { System.out.println("Database creation example!"); Connection con = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial","root","root"); try{ Statement st = con.createStatement(); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Database name:"); String database = bf.readLine();
  • 5. st.executeUpdate("CREATE DATABASE "+database); System.out.println("1 row(s) affacted"); } catch (SQLException s){ System.out.println("SQL statement is not executed!"); } } catch (Exception e){ e.printStackTrace(); } }}Download this example.Output of program:C:vinodjdbcjdbcjdbc-mysql>javacCreateDatabase.javaC:vinodjdbcjdbcjdbc-mysql>javaCreateDatabaseDatabase creation example!Enter Database name:RoseIndia1 row(s) affactedDatabase: A database is a large collection of data or information to stored in our computer in an arranged way. Ithelps us for accessing, managing and updating the data easily. In this example we are using MySQL database, whichis a RDBMS. A RDBMS (Relational Database Management System) is a type of DBMS (Database ManagementSystem) which stores the data in the form of tables. RDBMS is very powerful as it doesnt need to aware how the datais related or how it is going to be extracted from the database. So, we can view the same database in many differentways.Table: A table is basic component of database (DB) that has number of rows and columns. All tables are stored in aspecific database.Here we are providing you an example with code and its description that helps you to create a database table by usingjava file. Brief description given below:Description of program:Firstly in this program we are going to establish the connection with database and creating a table with some fields. Iftable name already exists then we are displaying the message "Table already exists!".Description of code:Statement:It is a interface. Statement object executes the SQL statement and returns the result it produces.createStatement():It is a method of Connection interface. which returns Statement object. This method will compile again and againwhenever the program runs.CREATE TABLE table_name(field_name):An appropriate code used for creating a table with given field name.
  • 6. executeUpdate(String table):This method also executes SQL statement that may be INSERT, UPDATE OR DELETE statement are used in thecode. It takes string types parameters for SQL statement. It returns int.Here is the code of program:import java.sql.*;public class CreateTable{ public static void main(String[] args) { System.out.println("Table Creation Example!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "jdbctutorial"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try{ Class.forName(driverName).newInstance(); con = DriverManager.getConnection(url+dbName, userName, password); try{ Statement st = con.createStatement(); String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))"; st.executeUpdate(table); System.out.println("Table creation process successfully!"); } catch(SQLException s){ System.out.println("Table all ready exists!"); } con.close(); } catch (Exception e){ e.printStackTrace(); } }}
  • 7. Terms of Agreement:By using this article, you agree to the following terms...1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.3) You may link to this article from another website, but ONLY if it is not wrapped in a frame.4) You will abide by any additional copyright restrictions which the author may have placed in the article or articles description.This tutorial will show you how to connect to a MySQL database using JSP (JavaServer Pages) underWindows and Tomcat web server. If you run into problems or find errors, please let me know so I canfine-tune this document. This document will probably be most useful for those who have done webscripting with MySQL databases before but would like to get started with JSP/Servlets programming.Database connectivity provides a good foundation for learning any new language, as you can practicemaking real-world applications in a database environment.Assumptions: 1. It is assumed that you already have a MySQL database installed and a table to pull data from. 2. It assumes you understand SQL, and probably have done some web/database scripting with other languages. 3. The author uses the folder C:Tomcat as the folder where Tomcat will be extracted, however, you can place the distribution files anywhere you wish. 4. You know the basics of programming Java. If you do not, I highly recommend you check out Suns Java Tutorial.Section A - Installation 1. Install the Java 2 JRE. I put mine in C:javajre, which will be used in this tutorial, but you can put your anywhere you like. 2. Extract the Tomcat distribution files to a folder. The default is jakarta-tomcat-4.1.12, but I chose to put the files in C:Tomcat. 3. Copy the MySQL Connector JAR file to the C:Tomcatcommonlib folder (ie, mysql- connector-java-2.0.14.jar).Section B - Environmental VariablesAdd the following environmental variables to Windows: JAVA_HOME=C:javajre TOMCAT_HOME=C:Tomcat You can set environmental variables in Windows 2000/XP by going to:Righy-click My Computer -> Properties -> Advanced -> Environmental VariablesYou can set environmental variables in Windows NT 4 by going to:Righy-click My Computer -> Properties -> EnvironmentSection C - Working with TomcatTo start the server, execute startup.bat. To stop the server, execute shutdown.bat in theC:Tomcatbin folder.By default, the Tomcat web server is access at this URL:http://localhost:8080/The root folder of the server is located in:C:TomcatwebappsROOTThe root and default port can be changed in this file:
  • 8. You would need the connector J from mysql inorder for the linkagehttp://dev.mysql.com/downloads/connector/j/3.1.htmlThis is a simple example...The minmum imports which is needed for a simple application could be:import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;You would then have to create a connection so place this within the classprivate Connection sqlConnection;To test if the driver is properly installed, you could add this function. This is for debugging purposes...public void testDriver() throws Exception {System.out.println("Initializing Server... ");try {Class.forName("org.gjt.mm.mysql.Driver");System.out.println(" Driver Found.");} catch (ClassNotFoundException e) {System.out.println(" Driver Not Found, exiting..");throw (e);}}And to connect to the database you do this, so then we have a returned the connection from the databases...:public Connection getConnection(String host, String userDB, String passDB, String database) throws Exception {String url = "";try {url = "jdbc:mysql://" + host + "/" + database;Connection con = DriverManager.getConnection(url, userDB, passDB);System.out.println(" Database connection established to " + url+ ".");return con;} catch (java.sql.SQLException e) {System.out.println(" Connection couldnt be established to "+ url);throw (e);}}
  • 9. You can write MySQL applications in a variety of languages. The languages that most people use with MySQL arePHP and Perl, but a sometimes overlooked option is the MySQL Connector/J driver, which allows you to developJava applications that interact with your MySQL server.MySQL Connector/J works within the framework of the Java JDBC interface, an API that allows Java programs touse database servers in a portable way. JDBC is based on an approach similar to that used in the design of Perl andRuby DBI modules, Pythons DB-API module, and PHPs PEAR::DB class. This approach uses a two-tierarchitecture: • The top level is visible to application programs and presents an abstract interface for connecting to and using database engines. The application interface does not depend on details specific to particular engines. • The lower level consists of drivers for individual database engines. Each driver handles the details necessary to map the abstract application interface onto operations that a specific engine will understand.The JDBC interface allows developers to write applications that can be used with different databases with a minimumof porting effort. Once a driver for a given server engine is installed, JDBC applications can communicate with anyserver of that type. By using MySQL Connector/J, your Java programs can access MySQL databases.Note: MySQL Connector/J is the successor to the MM.MySQL driver. If you have JDBC programs written forMM.MySQL, they should work with MySQL Connector/J as well, although you may want to update the driver classname used in your programs. Just replace instances of org.gjt.mm.mysql in your Java source files withcom.mysql.jdbc and recompile.Preliminary RequirementsTo use Java applications with MySQL, you may need to install some additional software: • If you want to compile and run Java programs, youll need a Java compiler (such as javac or jikes) and a runtime environment. If these are not already installed on your system, you can get them by obtaining a Java Software Development Kit (SDK) from java.sun.com. • If you want only to run precompiled applications, no compiler is necessary, but youll still need a Java Runtime Environment (JRE). This too may be obtained from java.sun.com.This article assumes that youll write and compile your own programs, and thus that you have a Java SDK installed.Once you compile a Java program, however, you can deploy it to other machines, even ones that have only a runtimeenvironment. This works even in heterogenous installations, because Java is platform-independent. Applicationscompiled on one platform can be expected to work on other platforms. For example, you can develop on a Linux boxand deploy on Windows.Connecting to the MySQL ServerTo connect to the MySQL server, register the JDBC driver you plan to use, then invoke its getConnection()method. The following short program, Connect.java, shows how to connect to and disconnect from a server runningon the local host. It accesses a database named test, using a MySQL account with a user name and password oftestuser and testpass: import java.sql.*; public class Connect {
  • 10. public static void main (String[] args) { Connection conn = null; try { String userName = "testuser"; String password = "testpass"; String url = "jdbc:mysql://localhost/test"; Class.forName ("com.mysql.jdbc.Driver").newInstance (); conn = DriverManager.getConnection (url, userName, password); System.out.println ("Database connection established"); } catch (Exception e) { System.err.println ("Cannot connect to database server"); } finally { if (conn != null) { try { conn.close (); System.out.println ("Database connection terminated"); } catch (Exception e) { /* ignore close errors */ } } } } }Compile Connect.java to produce a class file Connect.class that contains executable Java code: % javac Connect.javaThen invoke the class file as follows and it should connect to and disconnect from your MySQL server: % java Connect Database connection established Database connection terminatedIf you have trouble compiling Connect.java, double check that you have a Java Software Development Kit installedand make sure that the MySQL Connector/J driver is listed in your CLASSPATH environment variable.The arguments to getConnection() are the connection URL and the user name and password of a MySQL account.As illustrated by Connect.java, JDBC URLs for MySQL consist of jdbc:mysql:// followed by the name of theMySQL server host and the database name. An alternate syntax for specifying the user and password is to add themas parameters to the end of the connection URL: jdbc:mysql://localhost/test?user=testuser&password=testpassWhen you specify a URL using this second format, getConnection() requires only one argument. For example, thecode for connecting to the MySQL server in Connect.java could have been written like this: String userName = "testuser"; String password = "testpass"; String url = "jdbc:mysql://localhost/test?user=" + userName + "&password=" + password; Class.forName ("com.mysql.jdbc.Driver").newInstance (); conn = DriverManager.getConnection (url);getConnect() returns a Connection object that may be used to interact with MySQL by issuing queries andretrieving their results. (The next section describes how to do this.) When youre done with the connection, invoke itsclose() method to disconnect from the MySQL server.To increase the portability of your applications, you can store the connection parameters (host, database, user name,and password) in a Java properties file and read the properties at runtime. Then they need not be listed in the program
  • 11. itself. This allows you to change the server to which the program connects by editing the properties file, rather thanby having to recompile the program.Issuing QueriesTo process SQL statements in a JDBC-based application, create a Statement object from your Connection object.Statement objects support an executeUpdate() method for issuing queries that modify the database and return noresult set, and an executeQuery() method for queries that do return a result set. The query-processing examples inthis article use the following table, animal, which contains an integer id column and two string columns, name andcategory: CREATE TABLE animal ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id), name CHAR(40), category CHAR(40) )id is an AUTO_INCREMENT column, so MySQL automatically assigns successive values 1, 2, 3, ... as records are addedto the table.Issuing Queries That Return No Result SetThe following example obtains a Statement object from the Connection object, then uses it to create and populatethe animal table. DROP TABLE, CREATE TABLE, and INSERT all are statements that modify the database, soexecuteUpdate() is the appropriate method for issuing them: Statement s = conn.createStatement (); int count; s.executeUpdate ("DROP TABLE IF EXISTS animal"); s.executeUpdate ( "CREATE TABLE animal (" + "id INT UNSIGNED NOT NULL AUTO_INCREMENT," + "PRIMARY KEY (id)," + "name CHAR(40), category CHAR(40))"); count = s.executeUpdate ( "INSERT INTO animal (name, category)" + " VALUES" + "(snake, reptile)," + "(frog, amphibian)," + "(tuna, fish)," + "(racoon, mammal)"); s.close (); System.out.println (count + " rows were inserted");The executeUpdate() method returns the number of rows affected by a query. As shown above, the count is used toreport how many rows the INSERT statement added to the animal table.A Statement object may be used to issue several queries. When youre done with it, invoke its close() method todispose of the object and free any resources associated with it.Issuing Queries That Return a Result Set
  • 12. For statements such as SELECT queries that retrieve information from the database, use executeQuery(). Aftercalling this method, create a ResultSet object and use it to iterate through the rows returned by your query. Thefollowing example shows one way to retrieve the contents of the animal table: Statement s = conn.createStatement (); s.executeQuery ("SELECT id, name, category FROM animal"); ResultSet rs = s.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); System.out.println ( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); s.close (); System.out.println (count + " rows were retrieved");executeQuery() does not return a row count, so if you want to know how many rows a result set contains, youshould count them yourself as you fetch them.To obtain the column values from each row, invoke getXXX() methods that match the column data types. ThegetInt() and getString() methods used in the preceding example return integer and string values. As the exampleshows, these methods may be called using the name of a result set column. You can also fetch values by position. Forthe result set retrieved by the SELECT query in the example, id, name, and category are at column positions 1, 2 and3 and thus could have been obtained like this: int idVal = rs.getInt (1); String nameVal = rs.getString (2); String catVal = rs.getString (3);ResultSet objects, like Statement objects, should be closed when youre done with them.To check whether or not a column value is NULL, invoke the result set objects wasNull() method after fetching thevalue. For example, you could check for a NULL value in the name column like this: String nameVal = rs.getString ("name"); if (rs.wasNull ()) nameVal = "(no name available)";Using PlaceholdersSometimes its necessary to construct queries from values containing characters that require special treatment. Forexample, in queries, string values are written enclosed within quotes, but any quote characters in the string itselfshould be doubled or escaped with a backslash to avoid creating malformed SQL. In this case, its much easier to letJDBC handle the escaping for you, rather than fooling around trying to do so yourself. To use this approach, create adifferent kind of statement (a PreparedStatement), and refer to the data values in the query string by means ofplaceholder characters. Then tell JDBC to bind the data values to the placeholders and it will handle any specialcharacters automatically.Suppose you have two variables nameVal and catVal from which you want to create a new record in the animaltable. To do so without regard to whether or not the values contain special characters, issue the query like this: PreparedStatement s; s = conn.prepareStatement ( "INSERT INTO animal (name, category) VALUES(?,?)"); s.setString (1, nameVal);
  • 13. s.setString (2, catVal); int count = s.executeUpdate (); s.close (); System.out.println (count + " rows were inserted");The ? characters in the query string act as placeholders--special markers indicating where data values should beplaced. The setString() method takes a placeholder position and a string value and binds the value to theappropriate placeholder, performing any special-character escaping that may be necessary. The method you use tobind a value depends on the data type. For example, setString() binds string values and setInt() binds integervalues.Error HandlingIf you want to trap errors, execute your JDBC operations within a try block and use an exception handler to displayinformation about the cause of any problems that occur. JDBC provides getMessage() and getErrorCode()methods that may be invoked when an exception occurs to obtain the error message and the numeric error code. Thefollowing example deliberately issues a malformed query. When it runs, the executeQuery() method fails and raisesan exception that is handled in the catch block: try { Statement s = conn.createStatement (); s.executeQuery ("XYZ"); // issue invalid query s.close (); } catch (SQLException e) { System.err.println ("Error message: " + e.getMessage ()); System.err.println ("Error number: " + e.getErrorCode ()); }