There are the following steps are used by jdbc to retrieve the data
- A JDBC driver would be loaded
- Using the DriverManager a database Connection object would be created
- Using the Connection object a Statement object would be created
- Using the Statement object a SQL Select statement would be executed
- SQL select statement returned a ResultSet
- The ResultSet would be used to returned the rows and examine the data.
This example illustrates how to create a connection from database table and how to access row of the table:
import java.io.*; import java.sql.*;
public class JDBCMysqlConnection { public static void main( String args[]) { Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbname = "test"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root";
try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url+dbname,user,pass); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from tableName"); while (rs.next()){ System.out.println("Name= " + rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { con.close(); } } } |
No comments:
Post a Comment