database connectivity example
import java.sql.*;
public class ConnectDB
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/emp";
public static void main(String args[]);
{
Connection conn= null;
Statement stmt=null;
try
{
//step2:Register JDBC driver
class.forName("com.mysql.jdbc.Driver");
//STEP:3 open a connection
System.out.println("Connection to database..........");
conn= DriverManager.getConnection(DB_URL,"root""password");
//STEP:4 execute a query
System.out.println("creating statement............");
stmt=conn.creatStatement();
String sql;
sql="SELECT eid,age,Fname,Lname,FORM employees";
ResultSet rs=stmt.executeQuery(sql);
//STEP:5 extract data from result set
while(rs.next())
{
//Retrieve by column name
int id=rs.getInt("eid");
int age=rs.getInt("age");
String first=rs.getString("Fname");
String last=rs.getString("Lname");
//Display values
System.out.print("ID:"+id);
System.out.print("age:"age);
System.out.print("first name:"+first);
System.out.print("last name:"+last);
}
//STEP 6:Clean-up environment
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
// Handle errors for JDBC
se.printStackTrace();
}
System.out.println("goodbye!");
}
}
public class ConnectDB
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/emp";
public static void main(String args[]);
{
Connection conn= null;
Statement stmt=null;
try
{
//step2:Register JDBC driver
class.forName("com.mysql.jdbc.Driver");
//STEP:3 open a connection
System.out.println("Connection to database..........");
conn= DriverManager.getConnection(DB_URL,"root""password");
//STEP:4 execute a query
System.out.println("creating statement............");
stmt=conn.creatStatement();
String sql;
sql="SELECT eid,age,Fname,Lname,FORM employees";
ResultSet rs=stmt.executeQuery(sql);
//STEP:5 extract data from result set
while(rs.next())
{
//Retrieve by column name
int id=rs.getInt("eid");
int age=rs.getInt("age");
String first=rs.getString("Fname");
String last=rs.getString("Lname");
//Display values
System.out.print("ID:"+id);
System.out.print("age:"age);
System.out.print("first name:"+first);
System.out.print("last name:"+last);
}
//STEP 6:Clean-up environment
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
// Handle errors for JDBC
se.printStackTrace();
}
System.out.println("goodbye!");
}
}
Comments
Post a Comment