You are on page 1of 3

package init.

Ebay;
import java.sql.*;
public class Databasecmn
{
//Step 1: import java.sql.* => this will contain all JDBC - SQL
classes
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/Ebay";
// for windows 3306...mac 8889
//<server url>/<My database name>
static final String USER = "root";
//user and password for my database
static final String PASS = "";
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
//STEP 2: Register JDBC driver => this tell the compiler to use
this driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection => creates connection between applic
ation and database
System.out.println("Connecting to database...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();//connection
String sql;
sql = "SELECT name,salary,age,company FROM emp";
rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next())
{
//Retrieve by column name
String name =rs.getString("name");
int salary = rs.getInt("salary");
int age = rs.getInt("age");
String company =rs.getString("company");

//Display values
System.out.println("name: " +name);
System.out.println(" salary: " +salary);
System.out.println(" age " +age);
System.out.println(" company " +company);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se)
{
se.printStackTrace();
}catch(Exception e)
{
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();

}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
//end FirstExample
}

You might also like