Statement(I) in JDBC

public interface Statement
extends Wrapper, AutoCloseable

The object used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statementobjects. All execution methods in the Statement interface implicitly close a statment’s current ResultSet object if an open one exists.

Example:

package practice;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CheckInsertTable {
public static void main(String[] args) throws SQLException {
String url = “jdbc:oracle:thin:@localhost:1521:xe”;
String uname = “system”;
String pwd = “madhu”;
String Tablename = “Tagnames_companies”;
Check_Insert_Commit_Connection_Interface object = new Check_Insert_Commit_Connection_Interface();
Connection connection = object.makeConnection(url, uname, pwd);
connection.setAutoCommit(true);
Statement statement = connection.createStatement();
boolean b = object.checTableExists(connection, Tablename);
System.out.println(b);
if (!b) {
object.createNewTable(Tablename, statement);
boolean b2 = object.checTableExists(connection, Tablename);
System.out.println(b2);
if (b2) {
object.insetTheRecords(statement, Tablename);
object.readTheTable(Tablename, statement);
statement.close();
connection.close();
} else {
System.out.println(“Some problem…………!”);
}
} else {
System.out.println(“Table already exists…..!”);
}
}
}

class Check_Insert_Commit_Connection_Interface {
public boolean checTableExists(Connection connection, String tablename) throws SQLException {
Boolean boolean1 = false;
DatabaseMetaData md = connection.getMetaData();
String[] strings = { “TABLE” };
ResultSet rs = md.getTables(null, null, “%”, strings);
while (rs.next()) {
if (rs.getString(3).equalsIgnoreCase(tablename)) {
boolean1 = true;
}
}
return boolean1;
}

public void readTheTable(String tablename, Statement statement) throws SQLException {
ResultSet resultSet = statement.executeQuery(“select * from ” + tablename);
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
System.out.println(“————————————“);
}
}

public void insetTheRecords(Statement statement, String tablename) {
try {
statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
+ “VALUES (1,’Tcs’,’Experience The Certainity’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
+ “VALUES (2,’Infosys’,’Powered by Intellect,Driven by values’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
+ “VALUES (3,’Pega Sysytems’,’Build for the change’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void createNewTable(String tablename, Statement statement) {
String createTableSQL = “CREATE TABLE ” + tablename + “(” + “COMPANY_ID NUMBER(5) NOT NULL, ”
+ “COMPANYNAME VARCHAR(20) NOT NULL, ” + “COMPANYTAGNAME VARCHAR(40) NOT NULL, ”
+ “CREATED_DATE DATE NOT NULL, ” + “PRIMARY KEY (COMPANY_ID) ” + “)”;
try {
int no = statement.executeUpdate(createTableSQL);
System.out.println(no);
} catch (SQLException e) {
e.printStackTrace();
}
}

public Connection makeConnection(String url, String uname, String pwd) {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, uname, pwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;

}
}

output:

false
0
true
1
Tcs
Experience The Certainity
————————————
2
Infosys
Powered by Intellect,Driven by values
————————————
3
Pega Sysytems
Build for the change
————————————

db_comapanies_statement

Dis-advantages of Statement(I):

  • Only Static queries are available i.e no run time submission of arguments to a sql query.
  • SQL injection problem.

Advanatges:

  • In the long run, yes. If you are only running it once, no – but then it doesn’t matter because you are only running it once.
  • Best for DDL COMMANDS: CREATE,ALTER,DROP AND TRUNCATE.

    In practice you should always start with a PreparedStatement and only downgrade to a Statement if you have proven a performance problem.

Reference:

Statement Versus PreparedStatement

There’s a popular belief that using a PreparedStatement object is faster than using a Statement object. After all, a prepared statement has to verify its metadata against the database only once, while a statement has to do it every time. So how could it be any other way? Well, the truth of the matter is that it takes about 65 iterations of a prepared statement before its total time for execution catches up with a statement. This has performance implications for your application, and exploring these issues is what this section is all about.

When it comes to which SQL statement object performs better under typical use, a Statement or a PreparedStatement, the truth is that the Statement object yields the best performance. When you consider how SQL statements are typically used in an application–1 or 2 here, maybe 10-20 (rarely more) per transaction–you realize that a Statement object will perform them in less time than a PreparedStatement object. In the next two sections, we’ll look at this performance issue with respect to both the OCI driver and the Thin driver.

 

References:

 

 

Advertisements

Connection(I) in JDBC

public interface Connection
extends Wrapper, AutoCloseable

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object’s database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection’s configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection’s type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection’s type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);

 

The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData.

Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
Statement statement=connection.createStatement();

With the Connection(I) object help we are creating the statement .Similarlry,we can create for prepared and callable statements.

 

 

  • A sample program that checks if table is exists or not and it will create a new table and displays the contents of the table.Here we are using two  methods executeUpdate() and execute() etc.
  • executeUpdate

    int executeUpdate(String sql)
                      throws SQLException
    Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.Note:This method cannot be called on a PreparedStatement or CallableStatement.

    Parameters:
    sql – an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
    Returns:
    either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
    Throws:
    SQLException – if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces a ResultSet object, the method is called on a PreparedStatement or CallableStatement
    SQLTimeoutException – when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement

     

  • execute

    boolean execute(String sql)
                    throws SQLException
    Executes the given SQL statement, which may return multiple results. In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple results or (2) you are dynamically executing an unknown SQL string.The execute method executes an SQL statement and indicates the form of the first result. You must then use the methods getResultSet or getUpdateCount to retrieve the result, and getMoreResults to move to any subsequent result(s).

    Note:This method cannot be called on a PreparedStatement or CallableStatement.

    Parameters:
    sql – any SQL statement
    Returns:
    true if the first result is a ResultSet object; false if it is an update count or there are no results
    Throws:
    SQLException – if a database access error occurs, this method is called on a closed Statement, the method is called on a PreparedStatement or CallableStatement
    SQLTimeoutException – when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement
    See Also:
    getResultSet(), getUpdateCount(), getMoreResults()

     

  • package practice;

    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.Date;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class CheckInsertTable {
    public static void main(String[] args) throws SQLException {
    String url = “jdbc:oracle:thin:@localhost:1521:xe”;
    String uname = “system”;
    String pwd = “madhu”;
    String Tablename = “Tagnames_companies”;
    Check_Insert_Commit_Connection_Interface object = new Check_Insert_Commit_Connection_Interface();
    Connection connection = object.makeConnection(url, uname, pwd);
    connection.setAutoCommit(true);
    Statement statement = connection.createStatement();
    boolean b = object.checTableExists(connection, Tablename);
    System.out.println(b);
    if (!b) {
    object.createNewTable(Tablename, statement);
    boolean b2 = object.checTableExists(connection, Tablename);
    System.out.println(b2);
    if (b2) {
    object.insetTheRecords(statement, Tablename);
    object.readTheTable(Tablename, statement);
    statement.close();
    connection.close();
    } else {
    System.out.println(“Some problem…………!”);
    }
    } else {
    System.out.println(“Table already exists…..!”);
    }
    }
    }

    class Check_Insert_Commit_Connection_Interface {
    public boolean checTableExists(Connection connection, String tablename) throws SQLException {
    Boolean boolean1 = false;
    DatabaseMetaData md = connection.getMetaData();
    String[] strings = { “TABLE” };
    ResultSet rs = md.getTables(null, null, “%”, strings);
    while (rs.next()) {
    if (rs.getString(3).equalsIgnoreCase(tablename)) {
    boolean1 = true;
    }
    }
    return boolean1;
    }

    public void readTheTable(String tablename, Statement statement) throws SQLException {
    ResultSet resultSet = statement.executeQuery(“select * from ” + tablename);
    while (resultSet.next()) {
    System.out.println(resultSet.getString(1));
    System.out.println(resultSet.getString(2));
    System.out.println(resultSet.getString(3));
    System.out.println(“————————————“);
    }
    }

    public void insetTheRecords(Statement statement, String tablename) {
    try {
    statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
    + “VALUES (1,’Tcs’,’Experience The Certainity’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
    statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
    + “VALUES (2,’Infosys’,’Powered by Intellect,Driven by values’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
    statement.execute(“INSERT INTO ” + tablename + ” (COMPANY_ID,COMPANYNAME,COMPANYTAGNAME,CREATED_DATE) ”
    + “VALUES (3,’Pega Sysytems’,’Build for the change’,TO_DATE(‘1989-12-09′,’YYYY-MM-DD’))”);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    public void createNewTable(String tablename, Statement statement) {
    String createTableSQL = “CREATE TABLE ” + tablename + “(” + “COMPANY_ID NUMBER(5) NOT NULL, ”
    + “COMPANYNAME VARCHAR(20) NOT NULL, ” + “COMPANYTAGNAME VARCHAR(40) NOT NULL, ”
    + “CREATED_DATE DATE NOT NULL, ” + “PRIMARY KEY (COMPANY_ID) ” + “)”;
    try {
    int no = statement.executeUpdate(createTableSQL);
    System.out.println(no);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

    public Connection makeConnection(String url, String uname, String pwd) {
    Connection connection = null;
    try {
    connection = DriverManager.getConnection(url, uname, pwd);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return connection;

    }
    }

    output:

    false
    0
    true
    1
    Tcs
    Experience The Certainity
    ————————————
    2
    Infosys
    Powered by Intellect,Driven by values
    ————————————
    3
    Pega Sysytems
    Build for the change
    ————————————

     

DatabaseMetadata(I) in JDBC

  • public interface DatabaseMetaData
    extends Wrapper
  • omprehensive information about the database as a whole.This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBCTM technology (“JDBC driver”) that is used with it. Different relational DBMSs often support different features, implement features in different ways, and use different data types. In addition, a driver may implement a feature on top of what the DBMS offers. Information returned by methods in this interface applies to the capabilities of a particular driver and a particular DBMS working together. Note that as used in this documentation, the term “database” is used generically to refer to both the driver and DBMS.

    A user for this interface is commonly a tool that needs to discover how to deal with the underlying DBMS. This is especially true for applications that are intended to be used with more than one DBMS. For example, a tool might use the methodgetTypeInfo to find out what data types can be used in a CREATE TABLE statement. Or a user might call the method supportsCorrelatedSubqueries to see if it is possible to use a correlated subquery or supportsBatchUpdates to see if it is possible to use batch updates.

    Some DatabaseMetaData methods return lists of information in the form of ResultSet objects. Regular ResultSet methods, such as getString and getInt, can be used to retrieve the data from these ResultSet objects. If a given form of metadata is not available, an empty ResultSet will be returned. Additional columns beyond the columns defined to be returned by the ResultSet object for a given method can be defined by the JDBC driver vendor and must be accessed by their column label.

    Some DatabaseMetaData methods take arguments that are String patterns. These arguments all have names such as fooPattern. Within a pattern String, “%” means match any substring of 0 or more characters, and “_” means match any one character. Only metadata entries matching the search pattern are returned. If a search pattern argument is set to null, that argument’s criterion will be dropped from the search.

     

  • https://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html
  • A simple example on databasemaetadata(I)
  • ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)

    Retrieves a description of the tables available in the given catalog.
  • package practice;

    import java.sql.*;
    import oracle.jdbc.driver.*;

    class getVersion
    {
    public static void main (String args[])
    throws SQLException
    {
    // Load the Oracle JDBC driver
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    //Creates the Connection object
    Connection conn = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
    // Create Oracle DatabaseMetaData object
    DatabaseMetaData meta = conn.getMetaData();
    // gets driver info:
    System.out.println(“JDBC driver version is ” + meta.getJDBCMajorVersion());
    System.out.println(“JDBC driver name is”+meta.getDriverName());

    DatabaseMetaData md = conn.getMetaData();
    String[] strings={“TABLE”};
    ResultSet rs = md.getTables(null, null, “%”,strings);
    while (rs.next()) {
    System.out.println(rs.getString(3));
    }
    }
    }

    output:

    JDBC driver version is 11
    JDBC driver name isOracle JDBC driver
    APEX$_ACL
    APEX$_WS_FILES
    APEX$_WS_HISTORY
    APEX$_WS_LINKS
    APEX$_WS_NOTES
    APEX$_WS_ROWS
    APEX$_WS_TAGS
    APEX$_WS_WEBPG_SECTIONS
    APEX$_WS_WEBPG_SECTION_HISTORY
    SYS_IOT_OVER_16977
    WWV_COLUMN_EXCEPTIONS
    WWV_DEMO_DEPT
    WWV_DEMO_EMP
    WWV_FLOWS
    WWV_FLOWS_RESERVED
    WWV_FLOW_ACTIVITY_LOG1$
    WWV_FLOW_ACTIVITY_LOG2$
    WWV_FLOW_ACTIVITY_LOG_NUMBER$
    etc…………………………………………………………………..

Driver Manger Class in JDBC

  • public class DriverManager
    extends Object
  • It is the satatic class in java SDK.
  • First, you need to establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. Typically, a JDBC application connects to a target data source using one of two classes:

    DriverManager: This fully implemented class connects an application to a data source, which is specified by a database URL. When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within the class path. Note that your application must manually load any JDBC drivers prior to version 4.0.

    DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object’s properties are set so that it represents a particular data source. See Connecting with DataSource Objects for more information. For more information about developing applications with the DataSource class, see the latest The Java EE Tutorial.

  • //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  • Class.forName() is not directly related to JDBC at all. It simply loads a class.

    Most JDBC Driver classes register themselves in their static initializers by calling registerDriver().

    registerDriver() is the real call that you hardly ever need to call yourself (unless you write your own JDBC driver).

    Note that in JDBC 4 you should not need either of those if your JDBC driver is up-to-date, as drivers can be found using the service location mechanisms instead (i.e. simply leave out that call and open your connection as usual). See the documentaton of DriverManager for details:

    The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

    my.sql.Driver

    Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

     

  • Never call DriverManager.registerDriver() method manually. The JDBC spec requires a driver to register itself when the class is loaded, and the class is loaded via Class.forName(). In JDBC 4 the drivers are able to be loaded automatically just by being on the class path.

    DriverManager.registerDriver() manually is potentially dangerous since it actually causes the Driver to be registered twice. If your code requires you to deregister a Driver to prevent a memory leak then you would only end up deregistering it once and leave a second instance registered.

https://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html

http://www.ibm.com/support/knowledgecenter/ssw_i5_54/rzaha/db2drivr.htm

  • Example:
  • package practice;

    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class SimpleConnection {
    public static void main(String[] args) throws SQLException {
    String url=”jdbc:oracle:thin:@localhost:1521:xe”;
    String uname=”system”;
    String pwd=”madhu”;

    //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    try {
    Class.forName(“oracle.jdbc.driver.OracleDriver”);
    //Class.forName(“oracle.jdbc.driver.OracleDriver”).newInstance();
    //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);
    Statement statement=connection.createStatement();

    ResultSet resultSet=statement.executeQuery(“select * from contact”);
    while(resultSet.next()){
    System.out.println(resultSet.getString(1));
    }
    connection.close();
    }
    }

    output:

    madhu
    charan
    surbhi
    ammu
    indra

     

wordpress_db_statement

oracle ojdbc6.jar location: C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib

 

JDBC

  • JDBC stands for JAVA DATA BASE CONNECTIVITY.
  • It is used to establish and maintains the connection in between java application and the data base.
  • JDBC uses various types of drivers in order to maintain a connection with the data base.
  • What is API

    API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other. An API can be created for applications, libraries, operating systems, etc

  • There are many possible implementations of JDBC drivers. These implementations are categorized as follows:

    • Type 1: Drivers that implement the JDBC API as a mapping to another data access API, such as ODBC (Open Database Connectivity). Drivers of this type are generally dependent on a native library, which limits their portability. The JDBC-ODBC Bridge is an example of a Type 1 driver.Note: The JDBC-ODBC Bridge should be considered a transitional solution. It is not supported by Oracle. Consider using this only if your DBMS does not offer a Java-only JDBC driver.
    • Type 2: Drivers that are written partly in the Java programming language and partly in native code. These drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited. Oracle’s OCI (Oracle Call Interface) client-side driver is an example of a Type 2 driver.
    • Type 3: Drivers that use a pure Java client and communicate with a middleware server using a database-independent protocol. The middleware server then communicates the client’s requests to the data source.
    • Type 4: Drivers that are pure Java and implement the network protocol for a specific data source. The client connects directly to the data source.

    http://www.javatpoint.com/jdbc-driver

  • Data Source:  A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. This connection is represented by a Connection object.
  • The “type” refers to how the driver implements the API. The four types are:Type 1: JDBC-ODBC Bridge driver (Bridge)

    Type 2: Native-API/partly Java driver (Native)

    Type 3: AllJava/Net-protocol driver (Middleware)

    Type 4: All Java/Native-protocol driver (Pure)

    They will have different performance characteristics. See this link for a more detailed review.

  • The major features added in JDBC 4.0 include:
    1. Auto-loading of JDBC driver class
    2. Connection management enhancements
    3. Support for RowId SQL type
    4. DataSet implementation of SQL using Annotations
    5. SQL exception handling enhancements
    6. SQL XML support
  • package practice;

    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class SimpleConnection {
    public static void main(String[] args) throws SQLException {

    String url=”jdbc:oracle:thin:@localhost:1521:xe”;
    String uname=”system”;
    String pwd=”madhu”;

    //From jdbc 4.0 i.e from java 6.0
    //else need to call Class.forname()
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

    Connection connection = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”madhu”);

    ResultSet resultSet=statement.executeQuery(“select * from contact”);
    while(resultSet.next()){
    System.out.println(resultSet.getString(1));
    }
    connection.close();*/
    }
    }

    output:

  • madhu
    charan
    surbhi

 

 

Work vs Job

Job :

  • A noun
  • It is a regular work.You will get paid for the job.
  • Example : I don’t like my job,Its boring
  • Example : Do you have a full time job?
  • Example : Where are you doing your job?

Work:

  • It is a verb and an uncountable
  • Doing something to achieve something.
  • Example :I have some work to do at home.
  • Example: I have work from 5-7 Pm.

Miscellaneous in OS

Static vs Dynamic loading of memory:

Static: If we want a program to be loaded at compile time,You have to be get ready with the all the dependency files of main program by compile time only.The linker will links all files to the memory.

In computer science, a static library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, producing an object file and a stand-aloneexecutable.[1] This executable and the process of compiling it are both known as a static build of the program. Historically, libraries could only be static. Static libraries are either merged with other static libraries and object files during building/linking to form a single executable, or they may be loaded at run-time into the address space of the loaded executable at a static memory offset determined at compile-time/link-time.

https://en.wikipedia.org/wiki/Static_library

Dynamic:  If we want a program to be loaded at run time,Your compiler will compile all the dependency files of main program by run time.The DLL will links all files to the memory.

In computing, a dynamic linker is the part of an operating system that loads and links the shared libraries needed by an executable when it is executed (at “run time“), by copying the content of libraries from persistent storage to RAM, and filling jump tables and relocating pointers. The specific operating system and executable format determine how the dynamic linker functions and how it is implemented.

Linking is often referred to as a process that is performed when the executable is compiled, while a dynamic linker is a special part of an operating system that loads external shared libraries into a running process and then binds those shared libraries dynamically to the running process. This approach is also called dynamic linking or late linking.

https://en.wikipedia.org/wiki/Dynamic_linker

1)   What is static loading in programming language?

Static loading:-A piece of code can be loaded into RAM(Random access memory)before it is executed means after being loaded into the RAM it may or  may not be get executed.

Drawbacks in static loading

->wastage of memory during the program execution because allocation of memory occupied by the static loaded program so it releases when the execution is completed

->C is one of the static loading programming languages.

->static loading happened in structural programming language.

2)   2) What is dynamic loading in programming language?

Dynamic loading:-A piece of code can be loaded into RAM (Random access memory) when it is necessary to be executed.

Advantages:-

->Object oriented programming languages follows dynamic loading methodology.  Examples: – java,.net,c++ and etc

è It uses less time to execute the programs.

->even though we have less memory the program definitely executed.

Memory Management types:

  • Swapping
  • Paging
  • Segmentation

https://www.tutorialspoint.com/operating_system/os_memory_management.htm

https://www.youtube.com/watch?v=xAvC-MJ_Sz8

Fragmentation:

Internal(The size is too big than needed)

Extrenal(The size is too small than neede)

Why Paging is needed:

OS performs an operation for storing and retrieving data from secondary storage devices for use in main memory. Paging is one of such memory management scheme. Data is retrieved from storage media by OS, in the same sized blocks called as pages. Paging allows the physical address space of the process to be non contiguous. The whole program had to fit into storage contiguously.

Paging is to deal with external fragmentation problem. This is to allow the logical address space of a process to be noncontiguous, which makes the process to be allocated physical memory

Page Fault:

A page fault occurs when a program accesses a page that has been mapped in address space, but has not been loaded in the physical memory.

Page fault algorithms:

more at…….https://www.tutorialspoint.com/operating_system/os_virtual_memory.htm

 

 

 

Logical Address in OS

Logical Address:

  • Logical address is generated by the CPU.
  • If you are intended to run a program it has to be available in the location that is provided by the  Logical address .
  • All Applications runs based on the logical address only.They don’t interact with physical addresses directly.
  • It is a reference which is having access to physical memory.
  • The set of references(more than one) which are used by an application is called “LOGICAL ADDRESS SPACE“.
  • A logical address has to map with physical memory in order to run an application.
  • The set of all physical addresses that are mapped to the logical address is called “PHYSICAL ADDRESS SPACE“.
  • MEMORY MANAGEMENT UNIT is responsible for mapping the logical addresses to the physical address.It has many strategies to map the logical address to physical address like(Adding the relocation number to the logical address) etc.
  • Mapping can be done in 3 ways (COMPILE TIME(memory locations are known in advance and PA LA are going to be same),LOAD TIME(memory locations are not known and PA LA are going to be same) And EXECUTION TIME(Needs H/w involvement and PA LA Are going to be different).

 

WHY LOGICAL MEMORY IS IMPORTANT…?:

  • With out logical  memory if i want run a program i need push the entire process to disk .This is going to be tedious in the case of large processes.
  • I can’t use the memory which got allocated for another process  by another process.
  • Slack time(The time for navigation in disk drive) would become higher.
  • Read/Write operations on physically leads to information loss or corruption.

 

Links:

 

 

Java-Pass by value vs(>) Pass by reference

Does java fallows passbyValue or passbyReference?

                                   One of the most confusing stuff in the java programming.Java allows only passbyValue mechanism(If we pass a reference variable as a method parameter,Java internally takes the reference as normal java variable).The below code brief you about this.

package practice;

import java.awt.Point;

public class Demos {
public static void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point point=new Point(125, 125);
Point temp = arg1;
arg1 = arg2;
arg2 = point;
System.out.println(“X: ” + arg1.x + ” Y: ” +arg1.y);
System.out.println(“X: ” + arg2.x + ” Y: ” +arg2.y);
System.out.println(” “);
}
public static void tricky_refrence(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
arg2.setLocation(new Point(500, 500));
Point point=arg1;
arg1=arg2;
arg2=point;
System.out.println(“X: ” + arg1.x + ” Y: ” +arg1.y);
System.out.println(“X: ” + arg2.x + ” Y: ” +arg2.y);
System.out.println(” “);
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
Point pnt3 = new Point(0,0);
System.out.println(“X: ” + pnt1.x + ” Y: ” +pnt1.y);
System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(” “);
tricky(pnt1,pnt2);
System.out.println(“X: ” + pnt1.x + ” Y:” + pnt1.y);
System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(” “);
tricky_refrence(pnt2,pnt3);
System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(“X: ” + pnt3.x + ” Y:” + pnt3.y);

RefExample refExample=new RefExample(“SECOND”);
System.out.println(refExample.string);
tricky_refrenceobject(refExample);
System.out.println(refExample.string);
tricky_refrenceobjectargchange(refExample);
System.out.println(refExample.string);
int a=123;
changeValue(a);
System.out.println(a);
}
private static void changeValue(int a) {
a=10;
}
private static void tricky_refrenceobject(RefExample refExample) {
System.out.println(“——Changed the reference—-“);
RefExample refExample22=new RefExample(“THIRD”);
refExample=refExample22;
System.out.println(refExample.string);
}
private static void tricky_refrenceobjectargchange(RefExample refExample) {
System.out.println(“———We changed the reference argument—“);
refExample.string=”FORTH”;
System.out.println(refExample.string);
}
}

class RefExample{
public RefExample(String string2) {
this.string=string2;
}

public String string=”FIRST”;
}

 

X: 0 Y: 0
X: 0 Y: 0

X: 0 Y: 0
X: 125 Y: 125

X: 100 Y:100
X: 0 Y: 0

X: 500 Y: 500
X: 100 Y: 100

X: 100 Y: 100
X: 500 Y:500
SECOND
——Changed the reference—-
THIRD
SECOND
———We changed the reference argument—
FORTH
FORTH
123

 

-Thank you.