APJII lab 01

8 63 0
APJII lab 01

Đang tải... (xem toàn văn)

Thông tin tài liệu

LAB GUIDE – SEMESTER – ACCP I.10 COURSE: APJ II LAB: 01 JPI - Lab – Introduction to Java APJ II Lab 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 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 (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: : 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 2 JPI - Lab – Introduction to Java Three kinds of Statements Statement: 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: Method executeUpdate(): int executeQuery(): ResultSet - SQL Command INSERT, UPDATE, DELETE, and DDL SELECT 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: Run script below to create database and table in MSSQL Server 2005/2008: create database c1108g go use c1108g go create table Persons( 3 JPI - Lab – Introduction to Java id int primary key identity(1,1), name varchar(90) ) select 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'); 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 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"); 4 JPI - Lab – Introduction to Java } //Close Resources rs.close(); st.close(); connection.close(); }catch(SQLException e){ e.printStackTrace(); } } } 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: 5 JPI - Lab – Introduction to Java 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 import 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

Ngày đăng: 27/10/2019, 09:28

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan