JDBC Example With MySQL
JDBC Example With MySQL
Data types of MySQL and Java programming language are not same, its need some mechanism for transferring data between an database using MySQL data types and a application using Java data types.
Java Type String String String java.math.BigDecimal java.math.BigDecimal boolean byte short int long float double double byte [] byte [] byte [] java.sql.Date
Page 1
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, variablelength 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 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.
Prajapati Hitendra Page 2
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 the back- end.
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 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
Prajapati Hitendra
Page 4
After establishing the connection with MySQL database by using the JDBC driver, you will learn how we can create our database.
Prajapati Hitendra
Page 6
C:\vinod\jdbc\jdbc\jdbc-mysql>javac CreateDatabase.java C:\vinod\jdbc\jdbc\jdbc-mysql>java CreateDatabase Database creation example! Enter Database name: RoseIndia 1 row(s) affacted
Database: A database is a large collection of data or information to stored in our computer in an arranged way.
Prajapati Hitendra
Page 8
Dear user, consider a case where we need to store a java types in our database table. Now one question may arise in your mind that whether the MySQL supports java types or not.
Prajapati Hitendra
Page 9
st.executeUpdate(table); System.out.println(table); con.close(); } catch (SQLException s){ System.out.println ("Table is all ready exists!"); } } catch (Exception e){ e.printStackTrace(); } } } Download this example.
This section introduces you how to get the detailed information about the database table.
Prajapati Hitendra
Page 11
C:\vinod\jdbc\jdbc\jdbc-mysql>javac DiscriptionTable.java C:\vinod\jdbc\jdbc\jdbc-mysql>java DiscriptionTable See Description of Table Example! Enter table name: vk Field Type Null Key Default Extra id int(11) NO name char(1) YES
Prajapati Hitendra
Page 12
Prajapati Hitendra
Page 13
In database system it is very important to know about the tables. To work with this, it is very important to know how to retrieve a table and create a table in the database.
Prajapati Hitendra
Page 14
Prajapati Hitendra
Page 15
Output of program:
C:\vinod\jdbc\jdbc-mysql>javac AllTableName.java C:\vinod\jdbc\jdbc-mysql>java AllTableName Listing all table name in Database! Table name: employee employee11 employee2 employee3 employee4 employee5 employee6 employee8 employee9 java_datatypes java_datatypes2 javatypes Download this example.
After making the table in the database, we need to insert the values in the database. Here we are going to see, how we can insert values in the MySQL database table.
Download this example. Output of program: C:\vinod\jdbc\jdbc\jdbcmysql>javac InsertValues.java C:\vinod\jdbc\jdbc\jdbc-mysql>java InsertValues Inserting values in Mysql database table! 1 row affected
Prajapati Hitendra
Page 17
Prajapati Hitendra
Page 18
C:\vinod\jdbc\jdbc-mysql>java GetAllRows Getting All Rows from a table! Emp_code: Emp_name: 10 vinod 11 Amar 15 Aman 1 sushil
Download this example.
After creating a database table, if we want to know number of rows in a table then we can get it very easily by using the simple database query.
Prajapati Hitendra
Page 20
Here we are providing you an example with code that retrieves all columns name in a specific database table. Sometimes, you need to know the number of columns and the names of the columns of the table, so you can retrieve it with the help of this example.
C:\vinod\jdbc\jdbc-mysql>javac ColumnName.java C:\vinod\jdbc\jdbc-mysql>java ColumnName Getting Column Names Example! Number of Column : 2 Columns Name:
Prajapati Hitendra Page 22
In this jdbc tutorial program we are going to learn about adding a new column in database table.
Prajapati Hitendra
Page 23
Database Table: Student Table Stu_id Stu_name Stu_sub 100 101 102 103 vinod raju ranjan Aman computer math bio phy
Output of program: C:\vinod\jdbc\jdbc\jdbcmysql>javac AddColumn.java C:\vinod\jdbc\jdbc\jdbc-mysql>java AddColumn Adding new column in table example!
Prajapati Hitendra Page 24
This section provides you an example with code for renaming a column name in a database table.
Prajapati Hitendra
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac ChangeColumnName.java C:\vinod\jdbc\jdbc\jdbc-mysql>java ChangeColumnName Change column name in a database table example! Enter table name: Student Enter old column name: Stu_roll Enter new column: Stu_id Enter data type: integer Query OK, 4 rows affected After change the table will look like this Student Table Stu_id Stu_name Stu_sub 100 101 102 103 vinod raju ranjan Aman computer math bio phy
In this section you will learn, how to define a unique key in a column of a database table.
In this section you will learn, how to define a unique key in a column of a database table. While declaring unique key in a column we should check whether this column is eligible to store a unique values or not because if the column has been declared as unique then it can't store a duplicate values. If we ever try to insert the duplicate data in the unique column then it will show an error message to you that you are trying to insert the duplicate value. Description of program: After making a connection with the database firstly compile this program, only after that it will run, Now give the table name and column name to which you want to make a unique column. After assigning the unique key to a column the SQL statement is executed with the help of some java methods. If column name becomes unique then shows "Query OK, n rows affected." otherwise, displays a message "Table or column is not found!". Description of code: ALTER TABLE table_name ADD UNIQUE(col_name):; Above code is used to make unique of any column . It takes table name and column name. Here is the code of program:
import java.io.*; import java.sql.*; public class MakeUniqueColumn{ public static void main(String[] args) { System.out.println("Make unique column 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 table name: "); String table = bf.readLine(); System.out.println("Enter column name that you want to unique values: "); String col = bf.readLine(); int n = st.executeUpdate("ALTER TABLE "+table+" ADD UNIQUE"+"("+col+")"); System.out.println("Query OK, "+n+" rows affected."); } catch (SQLException s){ System.out.println("Table or column is not found!"); } } catch (Exception e){ e.printStackTrace(); }
Prajapati Hitendra
Page 28
Stu_id Stu_name Stu_sub Stu_marks 100 101 102 103 vinod raju ranjan Aman computer NULL math bio phy NULL NULL NULL
Output of program:
C:\vinod\jdbc\jdbc\jdbc-mysql>javac MakeUniqueColumn.java C:\vinod\jdbc\jdbc\jdbc-mysql>java MakeUniqueColumn Make unique column example! Enter table name: Student Enter column name that you want to unique values: Stu_id Query OK, 4 rows affected. Make unique values: Student Table Stu_id Stu_name Stu_sub Stu_marks 100 101 102 103 vinod raju ranjan Aman computer NULL math bio phy NULL NULL NULL
In this section, we will see how to remove unique field of the particular column in a database table. We know that, any table stores data in the form of rows and columns.
Prajapati Hitendra Page 29
Prajapati Hitendra
Page 30
Stu_id Stu_name Stu_sub Stu_marks 100 101 102 103 vinod raju ranjan Aman computer NULL math bio phy NULL NULL NULL
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac RemoveUniqueColumn.java C:\vinod\jdbc\jdbc\jdbc-mysql>java RemoveUniqueColumn Remove unique column example! Enter table name: Student Enter column name which has unique values: Stu_id Query OK, 5 rows affected. After removing the unique column from Database Table: Student Table Stu_id Stu_name Stu_sub Stu_marks 100 101 102 103 104 103 vinod raju ranjan Aman manoj Aman computer NULL math bio phy che phy NULL NULL NULL 50 85
Prajapati Hitendra
Page 31
This section will provide you the facility for arranging the data of database table in ascending order.
Prajapati Hitendra
Page 32
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac ColumnAscOrder.java C:\vinod\jdbc\jdbc\jdbc-mysql>java ColumnAscOrder Ascending order example! Enter table name: emp_sal Enter column name which have to see ascending order: Emp_sal Ascending order of given column: 600 4500 5000 8000 10000
Prajapati Hitendra Page 33
This section provides an example with code that arrange the records of database table in descending order.
Prajapati Hitendra
Page 34
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac ColumnDescOrder.java C:\vinod\jdbc\jdbc\jdbc-mysql>java ColumnDescOrder Descending order example! Enter table name: emp_sal Enter column name which have to see descending order: Emp_sal Descending order of given column: 10000 8000 5000 4500 600
This section provides an example with code that arrange the records of database table in descending order. The descending order provides a way for arranging records from largest to smallest in a sequence like: 100,85,45,12,......... See detail information below: Description of program: First of all in this program we are will establish the connection with MySQL database. As soon as the connection gets established it takes a table name and column name which we want to see in descending order. If the data gets arranged in descending order then it we are going to display the message "Descending order of given column:"........... otherwise shows a message "SQL statement is not executed!". Description of code: SELECT col_name FROM table_name ORDER BY col_name DESC: This query helps us to arrange the records of database table in descending order. The SELECT specifies the table columns that are retrieved. The FROM clause tells from where the tables has been accessed. The ORDER BY clause needed to us whenever, we want to sort the data of any column of the table. The DESC clause provides the facility to arrange the data in descending order (decrease order). Here is the code of program:
import java.io.*; import java.sql.*; public class ColumnDescOrder{ public static void main(String[] args) { System.out.println("Descending order 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 table name:"); String table = bf.readLine(); System.out.println("Enter column name which have to see descending order:"); String col_name = bf.readLine(); ResultSet res = st.executeQuery ("SELECT "+col_name+" FROM "+table+" ORDER BY "+col_name+" DESC"); System.out.println("Descending order of given column:"); while (res.next()){
Prajapati Hitendra
Page 36
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac ColumnDescOrder.java C:\vinod\jdbc\jdbc\jdbc-mysql>java ColumnDescOrder Descending order example! Enter table name: emp_sal Enter column name which have to see descending order: Emp_sal Descending order of given column: 10000 8000 5000 4500 600
This section describes how we can calculate the sum of specific column data in the database table.
Prajapati Hitendra
Page 38
C:\vinod\jdbc\jdbc\jdbcmysql>javac SumColumn.java C:\vinod\jdbc\jdbc\jdbc-mysql>java SumColumn Sum of the specific column! Enter table name: emp_sal Enter column name which have to sum: Emp_sal Sum of column = 28100
This section describes for deleting all rows from a specific database table.
Here is an example with code which provides the facility for deleting specific row in a database table.
Prajapati Hitendra
Page 41
In this section, we are going to learn how to delete a column from a database table
Prajapati Hitendra
Page 42
Stu_roll Stu_name Stu_sub Stu_marks 100 101 102 103 vinod raju ranjan Aman computer 95 math bio phy 89 80 85
Output of program:
C:\vinod\jdbc\jdbc\jdbc-mysql>javac DeleteColumn.java C:\vinod\jdbc\jdbc\jdbc-mysql>java DeleteColumn Delete columns example! Enter table name: Student Enter column name: Stu_marks Column is deleted successfully! After deleting a column: Student Table Stu_roll Stu_name Stu_sub 100 101 vinod raju computer math
Page 43
Prajapati Hitendra
In this section, we are going to see how to join two or more tables in a specific database.
Prajapati Hitendra
Page 45
Output of program:
C:\vinod\jdbc\jdbc\jdbc-mysql>javac NatJoinTable.java C:\vinod\jdbc\jdbc\jdbc-mysql>java NatJoinTable Natural Join Tables Example! Emp_name Emp_ed Emp_sal santosh 2 4500 Aman 13 8000
This section describes the NATURAL LEFT JOIN operation and how to retrieve data through it.
Emp_ed Emp_name
Prajapati Hitendra Page 47
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac NatLeftJoinTable.java C:\vinod\jdbc\jdbc\jdbc-mysql>java NatLeftJoinTable Natural Left Join Tables Example! Emp_name Emp_ed Emp_sal santosh 2 4500 deepak 10 0 Aman 13 8000
This section describes the NATURAL RIGHT JOIN operation of table in a specific database.
Prajapati Hitendra
Page 49
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac NatRightJoinTable.java C:\vinod\jdbc\jdbc\jdbc-mysql>java NatRightJoinTable Natural Right Join Tables Example! Emp_name Emp_ed Emp_sal Aman 13 8000 santosh 2 4500
This section introduces you to the cross join between two tables. The cross join operation retrieves data between two tables as a Cartesian product of set theory in mathematics.
Prajapati Hitendra
Page 51
Output of program: C:\vinod\jdbc\jdbc\jdbc-mysql>javac CrossJoinTable.java C:\vinod\jdbc\jdbc\jdbc-mysql>java CrossJoinTable Natural Left Join Tables Example! Emp_name Emp_ed Emp_sal santosh 2 8000 santosh 2 4500 deepak 10 8000 deepak 10 4500 Aman 13 8000 Aman 13 4500
In JDBC tutorial we are going to learn about the PreparedStatement and how to use with setObject method.
In JDBC tutorial we are going to learn about the PreparedStatement and how to use with setObject method. PreparedStatement: This is an interface of java.sql package which extends Statement interface. If you want to execute Statement object many times then we should use PreparedStatement object as it reduces the execution time. PreparedStatement object is faster than the Statement object as it is precompiled. In PreparedStatement we use IN parameter whose values are not known when the Sql statement is created. So we use "?" as a IN parameter and we also know it by the name of parameter marker. In this interface the modification has been done on the methods execute, executeQuery and executeUpdate. These methods are modified in such a way so that they take no argument. Description of program: In this program we are going to insert data in the database by using the setObject method of PreparedStatement interface. Before going into the details of the program we should firstly need to establish the connection with MySQL database by the help of JDBC driver. After establishing the connection now we will insert the data in setObject method. If the data gets added in the database table then it will display a message "Record is added in the table." otherwise it will show "SQL statement is not executed!". Description of code: prepareStatement(String sql): This method returns the PreparedStatement object for sending the parameterized SQL statement to the database that contains the pre-compiled SQL statement. Here the pre- compiled means once the statement has been compiled then it will not compile the same thing again. It takes the string type arguments which contains one or more '?' parameter placeholders. setObject(int par_index, object obj): It is used for setting the values of parameterized index by using the given object in this method. It takes two arguments to given below: par_index: It specifies the parameter like: the first is 1, second is 2, ...... object obj: It contains the parameter values to given by the users. Here is the code of program:
import java.sql.*; public class PreparedStatementSetObject{ public static void main(String[] args) { System.out.println("Prepared Statement Set Array Example!"); Connection con = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection
Prajapati Hitendra
Page 53
Database Table: emp_sal Emp_name Emp_sal ghtdfgl Raja Ram 5455 545
Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac PreparedStatementSetObject.java C:\vinod\jdbc\jdbc\PreparedStatement>java PreparedStatementSetObject Prepared Statement Set Array Example! 1 Record is added in the table. After executing the program: Database Table: emp_sal Emp_name Emp_sal ghtdfgl 5455 Raja Ram Sushil 545 15000
Page 54
Prajapati Hitendra
In this section we are going to learn about the batch update and how to use it. Here, we are providing an example with code to execute the statement in a batch.
This section helps to use the PreparedStatement with BatchUpdate and we are going to provide an example that performs batch update facility.
Prajapati Hitendra
Page 56
Prajapati Hitendra
Page 57
title year_made alam 1945 ara Karan 2005 Karan 2005 Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac PreparedStatementBatchUpdate.java C:\vinod\jdbc\jdbc\PreparedStatement>java PreparedStatementBatchUpdate Prepared Statement Batch Update Example! Added Successfully! After executing the program: Database Table: movies title alam ara Karan Karan year_made 1945 2005 2005
Bagal bali 2002 Raja 1998 Hindistani Diwar 1980 Nadia ke 1975 par
Prajapati Hitendra
Page 58
In this section we will learn how to select some specific records by using the PreparedStatement.
Prajapati Hitendra
Page 59
Database Table: movies title alam ara Karan Karan year_made 1945 2005 2005
Bagal bali 2002 Raja 1998 Hindistani Diwar 1980 Nadia ke 1975 par Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac SelectRecords.java C:\vinod\jdbc\jdbc\PreparedStatement>java SelectRecords Select Records Example by using the Prepared Statement! Bagal bali - 2002 Raja Hindustani - 1998 Diwar - 1980 Number of records: 3
Prajapati Hitendra Page 60
In this JDBC tutorial we are going to learn about the process of updating the records by using the PreparedStatement.
Prajapati Hitendra
Page 61
Bagal bali 2002 Raja 1998 Hindistani Diwar 1980 Nadia ke 1975 par
Output of program:
C:\vinod\jdbc\jdbc\PreparedStatement>javac UpdatesRecords.java C:\vinod\jdbc\jdbc\PreparedStatement>java UpdatesRecords Updates Records Example through Prepared Statement! Updating Successfully! After executing the program: Database Table: movies title alam ara Sanam We wafafa year_made 1945 2005
Prajapati Hitendra
Page 62
Bagal bali 2002 Raja 1998 Hindistani Diwar 1980 Nadia ke 1975 par
In this section we are going to learn how we will insert the records in the database table by using the PreparedStatement interface of java.sql package.
Prajapati Hitendra
Page 63
title year_made alam ara 1945 Bagal bali Diwar 2002 1980
Nadia ke 1975 par Karan Yarana 1996 1988 Ramayan 1966 Muhabte 1998
Prajapati Hitendra
Page 64
C:\vinod\jdbc\jdbc\PreparedStatement>javac InsertRecords.java C:\vinod\jdbc\jdbc\PreparedStatement>java InsertRecords Insert records example using prepared statement! Enter movie name: Bagban Enter releases year of movie: 2003 1row(s) affected After executing the program: Database table: movies table title year_made alam ara 1945 Bagal bali Diwar 2002 1980
Nadia ke 1975 par Karan Yarana Bagban 1996 1988 2003 Ramayan 1966 Muhabte 1998
In this section we will learn how to count all records of the database table by using the PreparedStatement interface of java.sql package.
In this section we will learn how to count all records of the database table by using the PreparedStatement interface of java.sql package. As we know that table keeps the records in tabular format like: rows and columns. A table has one or more records. If you will know that how many records in a database table then you get easily with the help of given program in RoseIndia.Net JDBC tutorial. See detailed information below: Description of program: This program helps us for counting the records of database table by using the PreparedStatement. For this, firstly we will establish the connection with MySQL database by using the JDBC driver. When connection has been established it takes a table name of database, only after that it will count the records of database table with the help of executeQuery method that returns a single ResultSet object and displays the number of records, otherwise it will show the message "SQL statement is not executed!". Here is the code of program:
import java.io.*; import java.sql.*; public class CountRecords{ public static void main(String[] args) { System.out.println("Count records example using prepared statement!"); Connection con = null; int records = 0; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/jdbctutorial","root","root"); try{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter table name:"); String table = bf.readLine(); String sql = "SELECT COUNT(*) FROM "+table; PreparedStatement prest = con.prepareStatement(sql); ResultSet rs = prest.executeQuery(); while (rs.next()){ records = rs.getInt(1); } System.out.println("Number of records: " + records); con.close(); } catch (SQLException s){ System.out.println("Table does not exist in the database!"); } } catch (Exception e){ e.printStackTrace(); }
Prajapati Hitendra
Page 66
title year_made alam ara 1945 Sanam We wafafa Sanam We wafafa Bagal bali Diwar 2005
Nadia ke 1975 par Karan Yarana 1996 1988 Ramayan 1966 Muhabte 1998 Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac CountRecords.java C:\vinod\jdbc\jdbc\PreparedStatement>java CountRecords Count records example using prepared statement! Enter table name: movies Number of records: 10
Prajapati Hitendra
Page 67
Prajapati Hitendra
Page 68
Database Table: movies title alam ara Bagal bali Karan Bagban Kuch kuch hota hi Ham hi tumahare sanam year_made 1945 2002 1996 2003 1985 1985
Output of the program: C:\vinod\jdbc\jdbc\PreparedStatement>javac DeleteRecords.java C:\vinod\jdbc\jdbc\PreparedStatement>java DeleteRecords Delete records example using prepared statement! Number of deleted records: 2 After executing the program: Database Table: movies title alam ara Bagal bali Karan year_made 1945 2002 1996
Page 69
Prajapati Hitendra
This JDBC tutorial helps us to use the PreparedStatement interface of java.sql package twice in a program.
Prajapati Hitendra
Page 70
Database Table: movies title alam ara Bagal bali Karan Bagban year_made 1945 2002 1996 2003
Prajapati Hitendra
Page 71
In this section we are going to learn the method for setting data types (String, int, float and double) in the PreparedStatement interface of java.sql package.
Prajapati Hitendra
Page 72
Stu_name Stu_marks Stu_ave Stu_total raju virendra deepak (NULL) 86 95 (NULL) (NULL) 35.255 32.5 56.05 41.52
Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac SetDataTypes.java C:\vinod\jdbc\jdbc\PreparedStatement>java SetDataTypes Set string,ingeger,double and float example by using the Prepared Statement! 1 row(s) affected) After executing the program:
Prajapati Hitendra Page 73
This tutorial teaches you the process of setting the byte, short and long data types in the PreparedStatement interface of the java.sql package.
Set byte, short and long data types by using the Prepared Statement
This tutorial teaches you the process of setting the byte, short and long data types in the PreparedStatement interface of the java.sql package. We know that the java and MySQL data types could not be same. But mapping is a mechanism to provide the facility for transferring the data to each other. For better understanding see the mapping between java and MySQL in the following explanation. Java data type MySQL data type byte tinyint (TINYINT) short smallint (SMALLINT) long bigint (BIGINT) Description of program: With the help of this program we are going to insert the byte, short and long data types in 'datatypes' table through the PreparedStatement interface of java.sql package. First of all, establish the connection with MySQL database by using the JDBC driver. After establishing the connection, it takes the SQL query in the prepareStatement and returns the PreparedStatement object. Now, we will insert different types of data like: byte, short and long by using the setByte, setShort and setLong methods. You will get the inserted data in the database table with a message "row(s) affected" otherwise it will display "SQL statement is not executed!". Description of code:
Prajapati Hitendra Page 74
d_type d_smt d_
Prajapati Hitendra Page 75
Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac SetByteSortLong.java C:\vinod\jdbc\jdbc\PreparedStatement>java SetByteSortLong Set Byte,short and long example by using Prepared Statement! 1 row(s) affected) After executing the program: Database Table: datatypes d_type d_smt d_ 7 8 10 35 65 352 6565 1556 6565 1556 6565 155645
In this JDBC section we are going to learn about the big decimal and how can be set it in the database table by using the PreparedStatement interface of java.sql package.
Prajapati Hitendra
Page 77
C:\vinod\jdbc\jdbc\PreparedStatement>javac SetBigDecimal.java C:\vinod\jdbc\jdbc\PreparedStatement>java SetBigDecimal Set BigDecimal Example! Successfully! Database Table: bigdecimal Records sal Rajesh 5.45152565625456e+032 Santhosh 5.45155487845426e+040 Tapan Deepak 5451554878454 5.45477514186419e+031
This JDBC tutorial helps us for setting date in the database table by using the PreparedStatement interface of java.sql package.
Prajapati Hitendra
Page 79
Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac SetDate.java C:\vinod\jdbc\jdbc\PreparedStatement>java SetDate Prepared statement set date example! 1 row(s) affected After executing the program: Database Table: Records Stu_roll Stu_name Admin_date 1 Raj kumar 1998-01-17 2 2 3 Santosh kashyap vinod kumar 1984-12-20
In this section you will learn about setting the time in database table by using the PreparedStatement interface of java.sql package.
Prajapati Hitendra
Page 81
Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac SetTime.java C:\vinod\jdbc\jdbc\PreparedStatement>java SetTime Prepared Statement Set Time example! 1 row(s) affectec) After executing the program: Database Table: child ch_name b_time Santosh vinod Deepak 12:08:36 02:01:00 09:45:57
In this JDBC tutorial we will teach how to set the Timestamp in database table by using the PreparedStatement interfac
Prajapati Hitendra
Page 83
Output of program: C:\vinod\jdbc\jdbc\PreparedStatement>javac SetTimetamp.java C:\vinod\jdbc\jdbc\PreparedStatement>java SetTimetamp Set Timestamp example by using the Prepared Statement! 1 row(s) affected) Database Table: ray rname rtime x-ray x-ray Bitaray 1984-11-25 02:25:45 1980-01-14 12:50:45 1984-11-23 13:01:00
Prajapati Hitendra
Page 84
Prajapati Hitendra
Page 85
In this section, you will learn to copy one table to another in a same MySQL database.
Prajapati Hitendra Page 86
Prajapati Hitendra
Page 87
Download this program. Table Name: employee empId 1 2 empName empSal Vinod Sushil 50000 80000
Table Name: Copyemployee empId 8 7 empName empSal AmarDeep 10000 Noor 50000
Output of this program: C:\vinod>javac CopyOneTableToAnother.java C:\vinod> C:\vinod>java CopyOneTableToAnother Copy data from one table to another in a database! 2 row(s)affected. C:\vinod> After copy table: Copyemployee empId 8 7 empName empSal AmarDeep 10000 Noor 50000
Page 88
Prajapati Hitendra
In this section, you will learn to copy one database table to another database table. That means we copy one table to a different table but it contains a similar type of field or column.
Prajapati Hitendra
Page 89
Download this program. Table Name: Copyemployee(jdbc4) empId 8 7 1 2 empName empSal AmarDeep 10000 Noor Vinod Sushil 50000 50000 80000
Table Name: Roseindia(jdbcMysql) empId 10 11 empName empSal Suman saurabh Ravi 19000 25000
Output of this program: C:\vinod>javac CopyOneDatabaseTableToAnother.java C:\vinod>java CopyOneDatabaseTableToAnother Copy data from one database table to another! 4 row(s)affected.
Prajapati Hitendra Page 90
In this example, we are inserting data into a MySQL database table using stored procedure.
Prajapati Hitendra
Page 93
In this section, you will learn to insert an image to the MySQL database table.
Prajapati Hitendra
Page 94
Download this code. Output of this Program: C:\Roseindia\vinod\jdbc4.0>javac insertImage.java C:\Roseindia\vinod\jdbc4.0>java insertImage Insert Image Example! Inserting Successfully! C:\Roseindia\vinod\jdbc4.0> Table Name: Image
Durga.jpg
Prajapati Hitendra
Page 95
In this Tutorial we want to explain you a code that makes you to understand JDBC MysqlConnection String.
Prajapati Hitendra
Page 96
Output
Jdbc Mysql Connection String : jdbc:mysql://localhost:3306/komal User Name :root Password :root
Download code
Prajapati Hitendra
Page 97