DBClass.java
Wednesday, December 29, 2010
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* * @author Jagadeesh
* if you like this example please follow my blog and
* submit your comments
*/
public class DBClass {
Connection con = null;
public Connection createConnection() throws
ClassNotFoundException,SQLException
{
//loading the driver. to use this driver you need to include
//mysql connector.jar files in tomcat server lib
//install mysql and sql yog and copy jar files and import
//database from sqlyog uisng tools-->import option
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/countrydb", "root", "root");
return connection;
}
public String getStates(String country)throws
SQLException, ClassNotFoundException
{
//creating connection by calling above method
Connection con = createConnection();
//using preparedstatement we are executing sql query(getting states)
PreparedStatement pstmt = con.prepareStatement
("select state from countries where country=?");
pstmt.setString(1, country);
ResultSet rs = pstmt.executeQuery();
String states="";
while(rs.next())
{
//getting states from database
states=rs.getString(1);
}
//this method returns string of states
return states;
}
public String getDistricts(String getstate)throws
SQLException, ClassNotFoundException
{
//creating connection by calling above method
Connection con = createConnection();
//using preparedstatement we are executing sql query(getting districts)
PreparedStatement pstmt = con.prepareStatement
("select Districtsnames from districts where state=?");
pstmt.setString(1, getstate);
ResultSet rs = pstmt.executeQuery();
String districts="";
while(rs.next())
{
districts=rs.getString(1);
}
//this method return districts as string.we will call this method
//in servlet
return districts;
}
}
Labels: