0% found this document useful (0 votes)
68 views

DataBase Connectivity

ODBC and JDBC allow applications to: 1) Open a connection to a database 2) Send queries and updates to the database 3) Receive results from the database They provide an API that applications can use to communicate with different database servers via a driver provided by the database vendor.

Uploaded by

cse viji2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

DataBase Connectivity

ODBC and JDBC allow applications to: 1) Open a connection to a database 2) Send queries and updates to the database 3) Receive results from the database They provide an API that applications can use to communicate with different database servers via a driver provided by the database vendor.

Uploaded by

cse viji2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 6

INTRODUCTION

Open DataBase Connectivity(ODBC) standard


 standard for application program to communicate with a database server.
 application program interface (API) to
o open a connection with a database,
o send queries and updates,
o get back results.

Applications such as GUI, spreadsheets, etc. can use ODBC

 Each database system supporting ODBC provides a "driver" library that must be linked with
the client program.
 When client program makes an ODBC API call, the code in the library communicates with
the server to carry out the requested action, and fetch results.
 ODBC program first allocates an SQL environment, then a database connection handle.
 Opens database connection using SQLConnect(). Parameters for SQLConnect:
o connection handle,
o the server to which to connect
o the user identifier,
o password
 Must also specify types of arguments:
o SQL_NTS denotes previous argument is a null-terminated string.

ODBC CODE

int ODBCexample()
{
RETCODE error;
HENV env; /* environment */
HDBC conn; /* database connection */
SQLAllocEnv(&env);
SQLAllocConnect(env, &conn);
SQLConnect(conn, "aura.bell-labs.com", SQL_NTS, "avi", SQL_NTS, "avipasswd",
SQL_NTS);
{ …. Do actual work … }
SQLDisconnect(conn);
SQLFreeConnect(conn);
SQLFreeEnv(env);
}

 Program sends SQL commands to the database by using SQLExecDirect


 Result tuples are fetched using SQLFetch()
 SQLBindCol() binds C language variables to attributes of the query result
 When a tuple is fetched, its attribute values are automatically stored in
corresponding C variables.
 Arguments to SQLBindCol()
 ODBC stmt variable, attribute position in query result
 The type conversion from SQL to C.
 The address of the variable.
 For variable-length types like character arrays,
o The maximum length of the variable
o Location to store actual length when a tuple is fetched.
o Note: A negative value returned for the length field indicates
null value

 Good programming requires checking results of every function call for errors; we have
omitted most checks for brevity.

 Main body of program

char branchname[80];
float balance;
int lenOut1, lenOut2;
HSTMT stmt;
SQLAllocStmt(conn, &stmt);
char * sqlquery = "select branch_name, sum (balance)
from account
group by branch_name";
error = SQLExecDirect(stmt, sqlquery, SQL_NTS);
if (error == SQL_SUCCESS) {
SQLBindCol(stmt, 1, SQL_C_CHAR, branchname , 80, &lenOut1);
SQLBindCol(stmt, 2, SQL_C_FLOAT, &balance, 0 , &lenOut2);
while (SQLFetch(stmt) >= SQL_SUCCESS) {
printf (" %s %g\n", branchname, balance);
}
}
SQLFreeStmt(stmt, SQL_DROP);

 Prepared Statement
o SQL statement prepared: compiled at the database
o Can have placeholders: E.g. insert into account values(?,?,?)
o Repeatedly executed with actual values for the placeholders

 Metadata features
o finding all the relations in the database and
o finding the names and types of columns of a query result or a relation in the
database.

 By default, each SQL statement is treated as a separate transaction that is committed


automatically.
o Can turn off automatic commit on a connection
 SQLSetConnectOption(conn, SQL_AUTOCOMMIT, 0)}
o transactions must then be committed or rolled back explicitly by
 SQLTransact(conn, SQL_COMMIT) or
 SQLTransact(conn, SQL_ROLLBACK)
ODBC Conformance level

 Conformance levels specify subsets of the functionality defined by the standard.


o Core
o Level 1 requires support for metadata querying
o Level 2 requires ability to send and retrieve arrays of parameter values and more
detailed catalog information.

 SQL Call Level Interface (CLI) standard similar to ODBC interface, but with some minor
differences.

JDBC

 JDBC is a Java API for communicating with database systems supporting SQL
 JDBC supports a variety of features for querying and updating data, and for retrieving query
results
 JDBC also supports metadata retrieval, such as querying about relations present in the
database and the names and types of relation attributes
 Model for communicating with the database:
o Open a connection
o Create a “statement” object
o Execute queries using the Statement object to send queries and fetch results
 Exception mechanism to handle errors

JDBC code

public static void JDBCexample(String dbid, String userid, String passwd)


{
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@aura.bell-
labs.com:2000:bankdb", userid, passwd);
Statement stmt = conn.createStatement();
… Do Actual Work ….
stmt.close();
conn.close();
}
catch (SQLException sqle) {
System.out.println("SQLException : " + sqle);
}
}

Update to database

try {
stmt.executeUpdate( "insert into account values
('A-9732', 'Perryridge', 1200)");
} catch (SQLException sqle) {
System.out.println("Could not insert tuple. " + sqle);
}
Execute query and fetch and print results

ResultSet rset = stmt.executeQuery( "select branch_name, avg(balance)


from account
group by branch_name");
while (rset.next()) {
System.out.println(
rset.getString("branch_name") + " " + rset.getFloat(2));
}

Getting result fields:

rs.getString(“branchname”) and rs.getString(1) equivalent if branchname is the first argument of


select result.

Dealing with Null values

int a = rs.getInt(“a”);
if (rs.wasNull()) Systems.out.println(“Got null value”);

Prepared statement

Prepared statement allows queries to be compiled and executed multiple times with different
arguments

PreparedStatement pStmt = conn.prepareStatement(


“insert into account values(?,?,?)”);
pStmt.setString(1, "A-9732");
pStmt.setString(2, "Perryridge");
pStmt.setInt(3, 1200);
pStmt.executeUpdate();
pStmt.setString(1, "A-9733");
pStmt.executeUpdate();

SQL sessions

 client connects to an SQL server, establishing a session


 executes a series of statements
 disconnects the session
 can commit or rollback the work carried out in the session

An SQL environment contains several components, including a user identifier, and a schema,
which identifies which of several schemas a session is using.

Schemas, Catalogs and Environments


 Three-level hierarchy for naming relations.
o Database contains multiple catalogs
o each catalog can contain multiple schemas
o SQL objects such as relations and views are contained within a schema
 e.g. catalog5.bank-schema.account
 Each user has a default catalog and schema, and the combination is unique to the user.
 Default catalog and schema are set up for a connection
 Catalog and schema can be omitted, defaults are assumed
 Multiple versions of an application (e.g. production and test) can run under separate
schemas

Transactions in JDBC

Application Architectures

 Applications can be built using one of two architectures


 Two tier model
o Application program running at user site directly uses JDBC/ODBC to communicate with the
database
 Three tier model
o Users/programs running at user sites communicate with an application server. The
application server in turn communicates with the database

Two-tier model

 E.g. Java code runs at client site and uses JDBC to communicate with the backend server
 Benefits:
o flexible, need not be restricted to predefined queries
 Problems:
o Security: passwords available at client site, all database operation possible
o More code shipped to client
o Not appropriate across organizations, or in large
ones like universities

Three –tier model


 E.g. Web client + Java Servlet using JDBC to talk with database server
 Client sends request over http or application-specific protocol
 Application or Web server receives request
 Request handled by CGI program or servlets
 Security handled by application at server
o Better security
o Fine granularity security
 Simple client, but only packaged transactions

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy