Unix Socket – Quick Guide

Unix Socket – Quick Guide ”; Previous Next What is a Socket? Sockets allow communication between two different processes on the same or different machines. To be more precise, it”s a way to talk to other computers using standard Unix file descriptors. In Unix, every I/O action is done by writing or reading a file descriptor. A file descriptor is just an integer associated with an open file and it can be a network connection, a text file, a terminal, or something else. To a programmer, a socket looks and behaves much like a low-level file descriptor. This is because commands such as read() and write() work with sockets in the same way they do with files and pipes. Sockets were first introduced in 2.1BSD and subsequently refined into their current form with 4.2BSD. The sockets feature is now available with most current UNIX system releases. Where is Socket Used? A Unix Socket is used in a client-server application framework. A server is a process that performs some functions on request from a client. Most of the application-level protocols like FTP, SMTP, and POP3 make use of sockets to establish connection between client and server and then for exchanging data. Socket Types There are four types of sockets available to the users. The first two are most commonly used and the last two are rarely used. Processes are presumed to communicate only between sockets of the same type but there is no restriction that prevents communication between sockets of different types. Stream Sockets − Delivery in a networked environment is guaranteed. If you send through the stream socket three items “A, B, C”, they will arrive in the same order − “A, B, C”. These sockets use TCP (Transmission Control Protocol) for data transmission. If delivery is impossible, the sender receives an error indicator. Data records do not have any boundaries. Datagram Sockets − Delivery in a networked environment is not guaranteed. They”re connectionless because you don”t need to have an open connection as in Stream Sockets − you build a packet with the destination information and send it out. They use UDP (User Datagram Protocol). Raw Sockets − These provide users access to the underlying communication protocols, which support socket abstractions. These sockets are normally datagram oriented, though their exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not intended for the general user; they have been provided mainly for those interested in developing new communication protocols, or for gaining access to some of the more cryptic facilities of an existing protocol. Sequenced Packet Sockets − They are similar to a stream socket, with the exception that record boundaries are preserved. This interface is provided only as a part of the Network Systems (NS) socket abstraction, and is very important in most serious NS applications. Sequenced-packet sockets allow the user to manipulate the Sequence Packet Protocol (SPP) or Internet Datagram Protocol (IDP) headers on a packet or a group of packets, either by writing a prototype header along with whatever data is to be sent, or by specifying a default header to be used with all outgoing data, and allows the user to receive the headers on incoming packets. What is Next? The next few chapters are meant to strengthen your basics and prepare a foundation before you can write Server and Client programs using socket. If you directly want to jump to see how to write a client and server program, then you can do so but it is not recommended. It is strongly recommended that you go step by step and complete these initial few chapters to make your base before moving on to do programming. Unix Socket – Network Addresses Before we proceed with the actual stuff, let us discuss a bit about the Network Addresses − the IP Address. The IP host address, or more commonly just IP address, is used to identify hosts connected to the Internet. IP stands for Internet Protocol and refers to the Internet Layer of the overall network architecture of the Internet. An IP address is a 32-bit quantity interpreted as four 8-bit numbers or octets. Each IP address uniquely identifies the participating user network, the host on the network, and the class of the user network. An IP address is usually written in a dotted-decimal notation of the form N1.N2.N3.N4, where each Ni is a decimal number between 0 and 255 decimal (00 through FF hexadecimal). Address Classes IP addresses are managed and created by the Internet Assigned Numbers Authority (IANA). There are five different address classes. You can determine which class an IP address is in by examining the first four bits of the IP address. Class A addresses begin with 0xxx, or 1 to 126 decimal. Class B addresses begin with 10xx, or 128 to 191 decimal. Class C addresses begin with 110x, or 192 to 223 decimal. Class D addresses begin with 1110, or 224 to 239 decimal. Class E addresses begin with 1111, or 240 to 254 decimal. Addresses beginning with 01111111, or 127 decimal, are reserved for loopback and for internal testing on a local machine [You can test this: you should always be able to ping 127.0.0.1, which points to yourself]; Class D addresses are reserved for multicasting; Class E addresses are reserved for future use. They should not be used for host addresses. Example Class Leftmost bits Start address Finish address A 0xxx 0.0.0.0 127.255.255.255 B 10xx 128.0.0.0 191.255.255.255 C 110x 192.0.0.0 223.255.255.255 D 1110 224.0.0.0 239.255.255.255 E 1111 240.0.0.0 255.255.255.255 Subnetting Subnetting or subnetworking basically means to branch off a network. It can be done for a variety of reasons like network in an organization, use of different physical media (such as Ethernet, FDDI, WAN, etc.), preservation of address space, and security. The most common reason is to control network traffic. The basic idea in subnetting is to partition the host identifier portion of the IP address into two parts − A

Unix Socket – Network Addresses

Unix Socket – Network Addresses ”; Previous Next Before we proceed with the actual stuff, let us discuss a bit about the Network Addresses − the IP Address. The IP host address, or more commonly just IP address, is used to identify hosts connected to the Internet. IP stands for Internet Protocol and refers to the Internet Layer of the overall network architecture of the Internet. An IP address is a 32-bit quantity interpreted as four 8-bit numbers or octets. Each IP address uniquely identifies the participating user network, the host on the network, and the class of the user network. An IP address is usually written in a dotted-decimal notation of the form N1.N2.N3.N4, where each Ni is a decimal number between 0 and 255 decimal (00 through FF hexadecimal). Address Classes IP addresses are managed and created by the Internet Assigned Numbers Authority (IANA). There are five different address classes. You can determine which class an IP address is in by examining the first four bits of the IP address. Class A addresses begin with 0xxx, or 1 to 126 decimal. Class B addresses begin with 10xx, or 128 to 191 decimal. Class C addresses begin with 110x, or 192 to 223 decimal. Class D addresses begin with 1110, or 224 to 239 decimal. Class E addresses begin with 1111, or 240 to 254 decimal. Addresses beginning with 01111111, or 127 decimal, are reserved for loopback and for internal testing on a local machine [You can test this: you should always be able to ping 127.0.0.1, which points to yourself]; Class D addresses are reserved for multicasting; Class E addresses are reserved for future use. They should not be used for host addresses. Example Class Leftmost bits Start address Finish address A 0xxx 0.0.0.0 127.255.255.255 B 10xx 128.0.0.0 191.255.255.255 C 110x 192.0.0.0 223.255.255.255 D 1110 224.0.0.0 239.255.255.255 E 1111 240.0.0.0 255.255.255.255 Subnetting Subnetting or subnetworking basically means to branch off a network. It can be done for a variety of reasons like network in an organization, use of different physical media (such as Ethernet, FDDI, WAN, etc.), preservation of address space, and security. The most common reason is to control network traffic. The basic idea in subnetting is to partition the host identifier portion of the IP address into two parts − A subnet address within the network address itself; and A host address on the subnet. For example, a common Class B address format is N1.N2.S.H, where N1.N2 identifies the Class B network, the 8-bit S field identifies the subnet, and the 8-bit H field identifies the host on the subnet. Print Page Previous Next Advertisements ”;

Unix Socket – Network Host Names

Unix Socket – Network Host Names ”; Previous Next Host names in terms of numbers are difficult to remember and hence they are termed by ordinary names such as Takshila or Nalanda. We write software applications to find out the dotted IP address corresponding to a given name. The process of finding out dotted IP address based on the given alphanumeric host name is known as hostname resolution. A hostname resolution is done by special software residing on high-capacity systems. These systems are called Domain Name Systems (DNS), which keep the mapping of IP addresses and the corresponding ordinary names. The /etc/hosts File The correspondence between host names and IP addresses is maintained in a file called hosts. On most of the systems, this file is found in /etc directory. Entries in this file look like the following − # This represents a comments in /etc/hosts file. 127.0.0.1 localhost 192.217.44.207 nalanda metro 153.110.31.18 netserve 153.110.31.19 mainserver centeral 153.110.31.20 samsonite 64.202.167.10 ns3.secureserver.net 64.202.167.97 ns4.secureserver.net 66.249.89.104 www.google.com 68.178.157.132 services.amrood.com Note that more than one name may be associated with a given IP address. This file is used while converting from IP address to host name and vice versa. You would not have access to edit this file, so if you want to put any host name along with IP address, then you would need to have root permission. Print Page Previous Next Advertisements ”;

Unix Socket – Structures

Unix Socket – Structures ”; Previous Next Various structures are used in Unix Socket Programming to hold information about the address and port, and other information. Most socket functions require a pointer to a socket address structure as an argument. Structures defined in this chapter are related to Internet Protocol Family. sockaddr The first structure is sockaddr that holds the socket information − struct sockaddr { unsigned short sa_family; char sa_data[14]; }; This is a generic socket address structure, which will be passed in most of the socket function calls. The following table provides a description of the member fields − Attribute Values Description sa_family AF_INET AF_UNIX AF_NS AF_IMPLINK It represents an address family. In most of the Internet-based applications, we use AF_INET. sa_data Protocol-specific Address The content of the 14 bytes of protocol specific address are interpreted according to the type of address. For the Internet family, we will use port number IP address, which is represented by sockaddr_in structure defined below. sockaddr in The second structure that helps you to reference to the socket”s elements is as follows − struct sockaddr_in { short int sin_family; unsigned short int sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; }; Here is the description of the member fields − Attribute Values Description sa_family AF_INET AF_UNIX AF_NS AF_IMPLINK It represents an address family. In most of the Internet-based applications, we use AF_INET. sin_port Service Port A 16-bit port number in Network Byte Order. sin_addr IP Address A 32-bit IP address in Network Byte Order. sin_zero Not Used You just set this value to NULL as this is not being used. in addr This structure is used only in the above structure as a structure field and holds 32 bit netid/hostid. struct in_addr { unsigned long s_addr; }; Here is the description of the member fields − Attribute Values Description s_addr service port A 32-bit IP address in Network Byte Order. hostent This structure is used to keep information related to host. struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list #define h_addr h_addr_list[0] }; Here is the description of the member fields − Attribute Values Description h_name ti.com etc. It is the official name of the host. For example, tutorialspoint.com, google.com, etc. h_aliases TI It holds a list of host name aliases. h_addrtype AF_INET It contains the address family and in case of Internet based application, it will always be AF_INET. h_length 4 It holds the length of the IP address, which is 4 for Internet Address. h_addr_list in_addr For Internet addresses, the array of pointers h_addr_list[0], h_addr_list[1], and so on, are points to structure in_addr. NOTE − h_addr is defined as h_addr_list[0] to keep backward compatibility. servent This particular structure is used to keep information related to service and associated ports. struct servent { char *s_name; char **s_aliases; int s_port; char *s_proto; }; Here is the description of the member fields − Attribute Values Description s_name http This is the official name of the service. For example, SMTP, FTP POP3, etc. s_aliases ALIAS It holds the list of service aliases. Most of the time this will be set to NULL. s_port 80 It will have associated port number. For example, for HTTP, this will be 80. s_proto TCP UDP It is set to the protocol used. Internet services are provided using either TCP or UDP. Tips on Socket Structures Socket address structures are an integral part of every network program. We allocate them, fill them in, and pass pointers to them to various socket functions. Sometimes we pass a pointer to one of these structures to a socket function and it fills in the contents. We always pass these structures by reference (i.e., we pass a pointer to the structure, not the structure itself), and we always pass the size of the structure as another argument. When a socket function fills in a structure, the length is also passed by reference, so that its value can be updated by the function. We call these value-result arguments. Always, set the structure variables to NULL (i.e., ””) by using memset() for bzero() functions, otherwise it may get unexpected junk values in your structure. Print Page Previous Next Advertisements ”;

Unix Socket – Useful Resources

Unix Socket – Useful Resources ”; Previous Next The following resources contain additional information on Unix Socket. Please use them to get more in-depth knowledge on this. Useful Video Courses Socket Programming in C from Scratch 11 Lectures 1 hours Eduonix Learning Solutions More Detail Network Socket programming in C Practical Way 8 Lectures 1.5 hours Musab Zayadneh More Detail Network sockets and streaming (C# based) 17 Lectures 1.5 hours Taurius Litvinavicius More Detail TCP/IP Socket Programming HandsOn-Windows & Linux in C & C++ 29 Lectures 9 hours Sonali Shrivastava More Detail Creating a Web Crawler in Python using Socket Programming 17 Lectures 2 hours Mgh Gh More Detail Create a 3D multi-player game using THREE.js and Socket.IO 35 Lectures 2.5 hours Nicholas Lever More Detail Print Page Previous Next Advertisements ”;

Unix Socket – Network Byte Orders

Unix Socket – Network Byte Orders ”; Previous Next Unfortunately, not all computers store the bytes that comprise a multibyte value in the same order. Consider a 16-bit internet that is made up of 2 bytes. There are two ways to store this value. Little Endian − In this scheme, low-order byte is stored on the starting address (A) and high-order byte is stored on the next address (A &plus; 1). Big Endian − In this scheme, high-order byte is stored on the starting address (A) and low-order byte is stored on the next address (A &plus; 1). To allow machines with different byte order conventions communicate with each other, the Internet protocols specify a canonical byte order convention for data transmitted over the network. This is known as Network Byte Order. While establishing an Internet socket connection, you must make sure that the data in the sin_port and sin_addr members of the sockaddr_in structure are represented in Network Byte Order. Byte Ordering Functions Routines for converting data between a host”s internal representation and Network Byte Order are as follows − Function Description htons() Host to Network Short htonl() Host to Network Long ntohl() Network to Host Long ntohs() Network to Host Short Listed below are some more detail about these functions − unsigned short htons(unsigned short hostshort) − This function converts 16-bit (2-byte) quantities from host byte order to network byte order. unsigned long htonl(unsigned long hostlong) − This function converts 32-bit (4-byte) quantities from host byte order to network byte order. unsigned short ntohs(unsigned short netshort) − This function converts 16-bit (2-byte) quantities from network byte order to host byte order. unsigned long ntohl(unsigned long netlong) − This function converts 32-bit quantities from network byte order to host byte order. These functions are macros and result in the insertion of conversion source code into the calling program. On little-endian machines, the code will change the values around to network byte order. On big-endian machines, no code is inserted since none is needed; the functions are defined as null. Program to Determine Host Byte Order Keep the following code in a file byteorder.c and then compile it and run it over your machine. In this example, we store the two-byte value 0x0102 in the short integer and then look at the two consecutive bytes, c[0] (the address A) and c[1] (the address A &plus; 1) to determine the byte order. #include <stdio.h> int main(int argc, char **argv) { union { short s; char c[sizeof(short)]; }un; un.s = 0x0102; if (sizeof(short) == 2) { if (un.c[0] == 1 && un.c[1] == 2) printf(“big-endiann”); else if (un.c[0] == 2 && un.c[1] == 1) printf(“little-endiann”); else printf(“unknownn”); } else { printf(“sizeof(short) = %dn”, sizeof(short)); } exit(0); } An output generated by this program on a Pentium machine is as follows − $> gcc byteorder.c $> ./a.out little-endian $> Print Page Previous Next Advertisements ”;

Java & MySQL – Drop Database

Java & MySQL – Drop Database Example ”; Previous Next This chapter provides an example on how to drop an existing Database using JDBC application. Before executing the following example, make sure you have the following in place − To execute the following example you need to replace the username and password with your actual user name and password. Your MySQL is up and running. NOTE − This is a serious operation and you have to make a firm decision before proceeding to delete a database because everything you have in your database would be lost. Required Steps The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database. Clean up the environment − try with resources automatically closes the resources. Sample Code Copy and paste the following example in TestApplication.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = “jdbc:mysql://localhost/”; static final String USER = “guest”; static final String PASS = “guest123”; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { String sql = “DROP DATABASE STUDENTS”; stmt.executeUpdate(sql); System.out.println(“Database dropped successfully…”); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac TestApplication.java C:> When you run TestApplication, it produces the following result − C:>java TestApplication Database dropped successfully… C:> Print Page Previous Next Advertisements ”;

Java & MySQL – SavePoint Transactions

Java & MySQL – SavePoint ”; Previous Next The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern DBMS, support savepoints within their environments such as Oracle”s PL/SQL. When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint. The Connection object has two new methods that help you manage savepoints − setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object. releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method. There is one rollback (String savepointName) method, which rolls back work to the specified savepoint. The following example illustrates the use of a Savepoint object − try{ //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt = conn.createStatement(); //set a Savepoint Savepoint savepoint1 = conn.setSavepoint(“Savepoint1”); String SQL = “INSERT INTO Employees ” + “VALUES (106, 20, ”Rita”, ”Tez”)”; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = “INSERTED IN Employees ” + “VALUES (107, 22, ”Sita”, ”Tez”)”; stmt.executeUpdate(SQL); // If there is no error, commit the changes. conn.commit(); }catch(SQLException se){ // If there is any error. conn.rollback(savepoint1); } In this case, none of the above INSERT statement would success and everything would be rolled back. Following is the example, which makes use of setSavepoint and rollback described. This sample code has been written based on the environment and database setup done in the previous chapters. Copy and paste the following example in TestApplication.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; public class TestApplication { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; static final String QUERY = “SELECT id, first, last, age FROM Employees”; static final String DELETE_QUERY = “DELETE FROM Employees WHERE ID = 8”; static final String DELETE_QUERY_1 = “DELETE FROM Employees WHERE ID = 9”; public static void printResultSet(ResultSet rs) throws SQLException{ // Ensure we start with first row rs.beforeFirst(); while(rs.next()){ // Display values System.out.print(“ID: ” + rs.getInt(“id”)); System.out.print(“, Age: ” + rs.getInt(“age”)); System.out.print(“, First: ” + rs.getString(“first”)); System.out.println(“, Last: ” + rs.getString(“last”)); } System.out.println(); } public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ) { conn.setAutoCommit(false); ResultSet rs = stmt.executeQuery(QUERY); System.out.println(“List result set for reference….”); printResultSet(rs); // delete row having ID = 8 // But save point before doing so. Savepoint savepoint1 = conn.setSavepoint(“ROWS_DELETED_1”); System.out.println(“Deleting row….”); stmt.executeUpdate(DELETE_QUERY); // Rollback the changes after save point 1. conn.rollback(savepoint1); // delete rows having ID = 9 // But save point before doing so. conn.setSavepoint(“ROWS_DELETED_2”); System.out.println(“Deleting row….”); stmt.executeUpdate(DELETE_QUERY_1); rs = stmt.executeQuery(QUERY); System.out.println(“List result set for reference….”); printResultSet(rs); // Clean-up environment rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } Now, let us compile the above example as follows − C:>javac TestApplication.java C:> When you run TestApplication, it produces the following result − C:>java TestApplication List result set for reference…. ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal ID: 5, Age: 40, First: John, Last: Paul ID: 7, Age: 20, First: Sita, Last: Singh ID: 8, Age: 20, First: Rita, Last: Tez ID: 9, Age: 20, First: Sita, Last: Singh Deleting row…. Deleting row…. List result set for reference…. ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal ID: 5, Age: 40, First: John, Last: Paul ID: 7, Age: 20, First: Sita, Last: Singh ID: 8, Age: 20, First: Rita, Last: Tez C:> Print Page Previous Next Advertisements ”;

Java & MySQL – Commit & Rollback

Java & MySQL – Commit & Rollback ”; Previous Next Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows − conn.commit( ); Otherwise, to roll back updates to the database made using the Connection named conn, use the following code − conn.rollback( ); The following example illustrates the use of a commit and rollback object − try{ //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String SQL = “INSERT INTO Employees ” + “VALUES (106, 20, ”Rita”, ”Tez”)”; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = “INSERTED IN Employees ” + “VALUES (107, 22, ”Sita”, ”Singh”)”; stmt.executeUpdate(SQL); // If there is no error. conn.commit(); }catch(SQLException se){ // If there is any error. conn.rollback(); } In this case, none of the above INSERT statement would success and everything would be rolled back. Following is the example, which makes use of commit and rollback described. This sample code has been written based on the environment and database setup done in the previous chapters. Copy and paste the following example in TestApplication.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; static final String QUERY = “SELECT id, first, last, age FROM Employees”; static final String INSERT_QUERY = “INSERT INTO Employees (first, last, age) values(”Rita”, ”Tez”, 20)”; static final String INSERT_QUERY_2 = “INSERT INTO Employees (first, last, age) values(”Sita”, ”Singh”, 20)”; public static void printResultSet(ResultSet rs) throws SQLException{ // Ensure we start with first row rs.beforeFirst(); while(rs.next()){ // Display values System.out.print(“ID: ” + rs.getInt(“id”)); System.out.print(“, Age: ” + rs.getInt(“age”)); System.out.print(“, First: ” + rs.getString(“first”)); System.out.println(“, Last: ” + rs.getString(“last”)); } System.out.println(); } public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ // Open a connection System.out.println(“Connecting to database…”); conn = DriverManager.getConnection(DB_URL,USER,PASS); // Set auto commit as false. conn.setAutoCommit(false); // Execute a query to create statment with // required arguments for RS example. System.out.println(“Creating statement…”); stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); // INSERT a row into Employees table System.out.println(“Inserting one row….”); stmt.executeUpdate(INSERT_QUERY); // INSERT one more row into Employees table stmt.executeUpdate(INSERT_QUERY_2); // Commit data here. System.out.println(“Commiting data here….”); conn.commit(); // Now list all the available records. String sql = “SELECT id, first, last, age FROM Employees”; ResultSet rs = stmt.executeQuery(sql); System.out.println(“List result set for reference….”); printResultSet(rs); // Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ se.printStackTrace(); // If there is an error then rollback the changes. System.out.println(“Rolling back data here….”); try{ if(conn!=null) conn.rollback(); }catch(SQLException se2){ se2.printStackTrace(); } }catch(Exception e){ e.printStackTrace(); }finally{ // finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ se2.printStackTrace(); } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } } Now let us compile the above example as follows − C:>javac TestApplication.java C:> When you run TestApplication, it produces the following result − C:>java TestApplication Connecting to database… Creating statement… Inserting one row…. Commiting data here…. List result set for reference…. ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal ID: 5, Age: 40, First: John, Last: Paul ID: 6, Age: 20, First: Rita, Last: Tez ID: 7, Age: 20, First: Sita, Last: Singh C:> Print Page Previous Next Advertisements ”;

Java & MySQL – CallableStatement

Java & MySQL – CallableStatement ”; Previous Next The CallableStatement interface is used to execute a call to a database stored procedure. Suppose, you need to execute the following stored procedure in TUTORIALSPOINT database − DELIMITER $$ DROP PROCEDURE IF EXISTS `TUTORIALSPOINT`.`getEmpName` $$ CREATE PROCEDURE `TUTORIALSPOINT`.`getEmpName` (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255)) BEGIN SELECT first INTO EMP_FIRST FROM Employees WHERE ID = EMP_ID; END $$ DELIMITER ; Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three. Here are the definitions of each − Parameter Description IN A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods. OUT A parameter whose value is supplied by the SQL statement it returns. You retrieve values from theOUT parameters with the getXXX() methods. INOUT A parameter that provides both input and output values. You bind variables with the setXXX() methods and retrieve values with the getXXX() methods. The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure − CallableStatement cstmt = null; try { String SQL = “{call getEmpName (?, ?)}”; cstmt = conn.prepareCall (SQL); . . . } catch (SQLException e) { . . . } finally { . . . } The String variable SQL, represents the stored procedure, with parameter placeholders. Using the CallableStatement objects is much like using the PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException. If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding. When you use OUT and INOUT parameters you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type, to the data type that the stored procedure is expected to return. Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type. Closing CallableStatement Object Just as you close other Statement object, for the same reason you should also close the CallableStatement object. A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup. CallableStatement cstmt = null; try { String SQL = “{call getEmpName (?, ?)}”; cstmt = conn.prepareCall (SQL); . . . } catch (SQLException e) { . . . } finally { cstmt.close(); } We”re using try with resources which handles the resource closure automatically. Following example demonstrates all of the above said concepts. This code has been written based on the environment and database setup done in the previous chapter. Copy and paste the following example in TestApplication.java, compile and run as follows − import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class TestApplication { static final String DB_URL = “jdbc:mysql://localhost/TUTORIALSPOINT”; static final String USER = “guest”; static final String PASS = “guest123”; static final String QUERY = “{call getEmpName (?, ?)}”; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); CallableStatement stmt = conn.prepareCall(QUERY); ) { // Bind values into the parameters. stmt.setInt(1, 102); // This would set ID // Because second parameter is OUT so register it stmt.registerOutParameter(2, java.sql.Types.VARCHAR); //Use execute method to run stored procedure. System.out.println(“Executing stored procedure…” ); stmt.execute(); //Retrieve employee name with getXXX method String empName = stmt.getString(2); System.out.println(“Emp Name with ID: 102 is ” + empName); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:>javac TestApplication.java C:> When you run TestApplication, it produces the following result − C:>java TestApplication Executing stored procedure… Emp Name with ID: 102 is Zaid C:> JDBC SQL Escape Syntax The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties. The general SQL escape syntax format is as follows − {keyword ”parameters”} Here are the following escape sequences, which you would find very useful while performing the JDBC programming − d, t, ts Keywords They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database”s format. For Example − {d ”yyyy-mm-dd”} Where yyyy = year, mm = month; dd = date. Using this syntax {d ”2009-09-03”} is March 9, 2009. Here is a simple example showing how to INSERT date in a table − //Create a Statement object stmt = conn.createStatement(); //Insert data ==> ID, First Name, Last Name, DOB String sql=”INSERT INTO STUDENTS VALUES” + “(100,”Zara”,”Ali”, {d ”2001-12-16”})”; stmt.executeUpdate(sql); Similarly, you can use one of the following two syntaxes, either t or ts − {t ”hh:mm:ss”} Where hh = hour; mm = minute; ss = second. Using this syntax {t ”13:30:29”} is 1:30:29 PM. {ts ”yyyy-mm-dd hh:mm:ss”} This is combined syntax of the above two syntax for ”d” and ”t” to represent timestamp. escape Keyword This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters.