In this example we will show you how to connect to MySQL database and perform select operation. You will learn the JDBC steps necessary to connect to the MySQL Database and execute the query.
In this example we will show you how to connect to MySQL database and perform select operation. You will learn the JDBC steps necessary to connect to the MySQL Database and execute the query.In this example we will show you how to connect to MySQL database and perform select operation. You will learn the JDBC steps necessary to connect to the MySQL Database and execute the query.
Here we are using the MySQL jdbc driver for making the connection. You can download the jdbc driver for MySQL from http://dev.mysql.com/downloads/connector/j/5.1.html and then put the driver jar file into the classpath.
You have to first create the a table in MySQL database and then connect it through JDBC to show all the records present there.
MySql Table Structure:
CREATE TABLE `servlet` ( `id` int(11) NOT NULL auto_increment, `name` varchar(256) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*Data for the table `servlet` */ insert into `servlet`(`id`,`name`) values (1,'sandeep'),(2,'amit'),(3,'anusmita'),(4,'vineet'); |
Here is the code of Example:
// *DataBase Connectivity from the Servlet. |
Program Description:
The following query is used to fetch the records from database and display on the screen.
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM servlet");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());//You
can also user rs.getString(1);
out.print("\t\t\t");
out.print(rs.getObject(2).toString());//You
can also user rs.getString(2);
out.print("<br>");
}
Other JDBC statement you can understand easily.
Output:
Ads