- Adding JDBC Driver Type 4 file sqljdbc4.jar library to your class path - Loading Driver try { Class.forName”com.microsoft.sqlserver.jdbc.SQLServerDriver”; //Or any other driver } catch
Trang 1LAB GUIDE – SEMESTER 2 – ACCP I.10
COURSE: APJ II
LAB: 01
Trang 2APJ II Lab 1
Objectives:
In this session, you will be practicing with:
JDBC driver type IV
JDBC application development process
Statement class
PreparedStatement class
ResultSet interface
ResultSetMetaData
Part I: Workshop – 15 minutes
1 Students open workshop in CD ROM, then View, Run, Think about it (10 minutes)
Part II: Step by step – 45 minutes
Guide 01: Step to connect to MSSQL Server 2005/2008 using JDBC Driver Type 4:
- Create Application Project in Netbeans
- Adding JDBC Driver Type 4 (file sqljdbc4.jar) library to your class path
- Loading Driver
try {
Class.forName(”com.microsoft.sqlserver.jdbc.SQLServerDriver”); //Or any other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}
- Create JDBC Connection: Using getConnection( ) of DriverManager for getting connection to
database It uses username, password, and JDBC url
JDBC URL Syntax:: jdbc: <subprotocol>: <subname>
String url = "jdbc:sqlserver://localhost:1433;databaseName=c1108g";
String username="sa";
String password= "12345678";
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected: " + connection);
- Create Statement Object
Three kinds of Statements
Trang 3Statement: Execute simple sql queries without parameters.
Statement createStatement()
Creates an SQL Statement object
Prepared Statement: Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object PreparedStatement objects are precompiled
SQL statements
Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
returns a new CallableStatement object CallableStatement objects are SQL stored procedure call statements
In these practices, you will use Statement, or PreparedStatement
Statement st = connection.createStatement();
PreparedStatement prst = conn.prepareStatement(sql);
Statement methods:
- Executing a SELECT statement with the Statement object, and returning a JDBC ResultSet
String query = "select * from persons";
ResultSet rs = st.executeQuery(query);//using for select
//Moi lan rs.next() thi se chuyen sang dong tiep theo
while(rs.next()){
String name = rs.getString(2);
System.out.println("Name: " + name);
}
- Executing a modify statement with the Statement object, and returning number of modified values String query = "INSERT INTO PERSONS VALUES('Phuong')";
int i = st.executeUpdate(query);//executeUpdate using for Insert, update, delete
if(i> 0){
System.out.println("Inserted");
}else{
System.out.println("No row affected");
}
Example 01: Following codes show how to establish connection to database and using Statement
object to retrieve data and modify data:
1 Run script below to create database and table in MSSQL Server 2005/2008:
create database c1108g
go
use c1108g
go
create table Persons(
id int primary key identity(1,1), name varchar(90)
Trang 4select t.*, CONVERT(varchar,getdate(),103) current_day from persons t
insert into Persons values('Luong');
insert into Persons values('Luong1');
insert into Persons values('Luong2');
2 Create class named Connector: in this example, you use Statement without parameterized
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connector {
public static void main(String[] args) throws Exception{
try{
//Tao ket noi database
//Buoc 01: Register Driver Approach 01
//com.microsoft.sqlserver.jdbc.SQLServerDriver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
//Approach 02 for reistering driver:
//DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
//Buoc 02: tao ket noi
String url = "jdbc:sqlserver://localhost:1433;databaseName=c1108g";
String username="sa";
String password= "12345678";
Connection connection = DriverManager.getConnection(url, username, password);
//Co the gap mot so loi: khong ket noi duoc cong, sai URL, sai username, password
System.out.println("Connected: " + connection);
//Buoc 03: Thuc thi cac cau lenh
//Buoc 03.01: Tao ra statement
Statement st = connection.createStatement();
//Buoc 03.02 (optiinal): select table, return resultset
String query = "select * from persons";
ResultSet rs = st.executeQuery(query);//using for select
//Moi lan rs.next() thi se chuyen sang dong tiep theo
while(rs.next()){
String name = rs.getString(2);
System.out.println("Name: " + name);
}
//Buoc 03.03: Cac cau lenh update neu co
query = "INSERT INTO PERSONS VALUES('Phuong')";
int i = st.executeUpdate(query);//executeUpdate using for Insert, update, delete
if(i> 0){
System.out.println("Inserted");
}else{
System.out.println("No row affected");
}
//Close Resources
rs.close();
Trang 5st.close();
connection.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
3
2 Class named PreparedStatementDemo: using statement object with parameterized
(PreparedStatement)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class PreparedStatementDemo {
public static void main(String[] args) throws Exception {
//Tao ket noi database
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
String url = "jdbc:sqlserver://localhost:1433;databaseName=C1108G";
Connection conn = DriverManager.getConnection(url, "sa", "12345678");
String sql = "select * from persons where name like ?";
PreparedStatement prst = conn.prepareStatement(sql);
//Cai dat tham so
prst.setString(1, "PHuong");
ResultSet rs = prst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(2));
}
//Insert, Update, delete
sql = "update persons set name = ? where id=?";
prst = conn.prepareStatement(sql);
prst.setString(1, "Trung XYZQ");
prst.setInt(2, 5);
prst.executeUpdate();
rs.close();
prst.close();
conn.close();
}
}
Guide 02: Using ResultSetMetaData:
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet It is constructed from the Connection object
Example 02: Using ResultSetMetaData
Trang 6import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class DatabaseMetaInfo {
public static void main(String[] args) throws Exception{
//Tao ket noi database
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
String url = "jdbc:sqlserver://localhost:1433;databaseName=C1108G";
Connection conn = DriverManager.getConnection(url, "sa", "12345678");
//Get Database Metadata
DatabaseMetaData metaData = conn.getMetaData();
String databaseProductName = metaData.getDatabaseProductName();
String databaseProductVersion = metaData.getDatabaseProductVersion();
System.out.printf("Name: %s Version: %s\n", databaseProductName,databaseProductVersion); PreparedStatement prst = conn.prepareStatement("select t01.*,getdate() as current_day from persons t01");
//get result meta data
ResultSet rs = prst.executeQuery();
ResultSetMetaData rsMeta = rs.getMetaData();
for(int i = 1; i<= rsMeta.getColumnCount(); i++){
String columnName = rsMeta.getColumnName(i);
System.out.println("COLUMN NAME: " + columnName);
}
//Close Resource
rs.close();
conn.close();
}
}
Part III: Do it yourself – 60 minutes
Exercise 1: By extending from two examples above, you write 2 programs as below:
Trang 7When user clicked on Add, program automatically add new record to database, and display it to the JTable
Building program shown in next figure:
Trang 8Exercise 2: Write a Java application StudentDetails that will add, modify and delete records from a student table The student table has the structure as shown in this table:
Column Name
Data Type
Rollno Numeric Class Varchar The output of the program is as shown as below.
Part IV: Homework
Exercise 1: Do assignment of module 1 in CD ROM
References
1) CD ROM APJ II, Aptech Education
2) http://docs.oracle.com/javase/tutorial/jdbc/basics/