Examples Of JDBC

When a Java application needs a database connection, one of the DriverManager.getConnection() methods is used to create a JDBC connection. The URL used is dependent upon the particular database and JDBC driver. It will always begin with the "jdbc:" protocol, but the rest is up to the particular vendor.

Connection conn = DriverManager.getConnection( "jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" );
try {

/* you use the connection here */

} finally {

//It's important to close the connection when you are done with it

try { conn.close(); } catch (Throwable e) { /* Propagate the original exception

instead of this one that you want just logged */

logger.warn("Could not close JDBC Connection",e); }
}

Starting from Java SE 7 you can use Java's try-with-resources statement to make the above code cleaner:

try (Connection conn = DriverManager.getConnection( "jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" ) ) { /* you use the connection here */}


Download Source code 'Java Database Connectivity'

Once a connection is established, a statement can be created.

try (Statement stmt = conn.createStatement()) {

stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );
}

Note that Connections, Statements, and ResultSets often tie up operating system resources such as sockets or file descriptors. In the case of Connections to remote database servers, further resources are tied up on the server, e.g., cursors for currently open ResultSets.
It is vital to close() any JDBC object as soon as it has played its part; garbage collection should not be relied upon. The above try-with-resources construct is a code pattern that obviates this.

Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query.



try (Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" )
) {
    while ( rs.next() ) {
        int numColumns = rs.getMetaData().getColumnCount();
        for ( int i = 1 ; i <= numColumns ; i++ ) {
           // Column numbers start at 1.
           // Also there are many methods on the result set to return
           //  the column as a particular type. Refer to the Sun documentation
           //  for the list of valid conversions.
           System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
        }
    }
} 

  
   

An example of a PreparedStatement query, using conn and class from first example.



    try (PreparedStatement ps =
    conn.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j WHERE i.name = ? AND j.num = ?" )
){
    // In the SQL statement being prepared, each question mark is a placeholder
    // that must be replaced with a value you provide through a "set" method invocation.
    // The following two method calls replace the two placeholders; the first is
    // replaced by a string value, and the second by an integer value.
    ps.setString(1, "Poor Yorick");
    ps.setInt(2, 8008);

    // The ResultSet, rs, conveys the result of executing the SQL statement.
    // Each time you call rs.next(), an internal row pointer, or cursor,
    // is advanced to the next row of the result.  The cursor initially is
    // positioned before the first row.
    try (ResultSet rs = ps.executeQuery()) {
        while ( rs.next() ) {
            int numColumns = rs.getMetaData().getColumnCount();
            for ( int i = 1 ; i <= numColumns ; i++ ) {
                // Column numbers start at 1.
                // Also there are many methods on the result set to return
                // the column as a particular type. Refer to the Sun documentation
                // for the list of valid conversions.
                System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
            } // for
        } // while
    } // try
} // try
    

If a database operation fails, JDBC raises an SQLException. There is typically very little one can do to recover from such an error, apart from logging it with as much detail as possible. It is recommended that the SQLException be translated into an application domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user.




    boolean autoCommitDefault = conn.getAutoCommit();
    try {
    conn.setAutoCommit(false);

    /* You execute statements against conn here transactionally */
    conn.commit();
    } catch (Throwable e) {
    try { conn.rollback(); } catch (Throwable e) { logger.warn("Could not rollback transaction",e); }
    throw e;
    } finally {
    try { conn.setAutoCommit(autoCommitDefault); } catch (Throwable e) { logger.warn("Could not restore AutoCommit setting",e); }
  }
    

For an example of a CallableStatement (to call stored procedures in the database), see the Java SE 9 documentation.


    import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Mydb1 {
   static String URL = "jdbc:mysql://localhost/mydb";

   public static void main(String[] args) {
      try{
        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection(URL,"root","root");
        Statement stmt = conn.createStatement();
      
        String sql = "INSERT INTO emp1 VALUES ('pctb5361','gajanan','krpuram',968666668)";
        stmt.executeUpdate(sql);
           
        System.out.println("Inserted records into the table...");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
    

References : wikipedia oracle « Privious Post » share on :        :  

Love to hear your Views / Guidance / Recommendations on this Post…

Explore the Technology World

Computer Programming Terminologies Computer Programming Terminology is a general word for the group of specialized words or meanings relating to Computer Programming, and also the study of such t ...Read MoreNew features in JDK 12 with IntelliJ IDEADeveloped by JetBrains (formerly known as IntelliJ) ,IntelliJ IDEA is a Java integrated development environment (IDE) for developing computer software. It is av ...Read MoreGoogle Pay API Implementation Demo for AndroidIn this youtube Channel by Android Developers ,Learn how to implement the Google Pay API for Android with just a few lines of code and how it works with your ex ...Read MoreUnit Testing in .NET Core and Azure Devops pipelineUnit testing is a software testing method by which individual units of source code, usage procedures,sets of one or more computer program modules together with ...Read MoreThe mind behind Linux & GIT : Linus TorvaldsLinus Torvalds transformed technology twice — first with the Linux kernel, which helps power the Internet, and again with Git, the source code management ...Read MoreTensorflow and deep learningWith Tensorflow ,deep machine learning transitions from an area of research into mainstream software engineering. ...Read MoreJava program to return all possible permutations from collection of distinct numbersexample of Java program to return all possible permutations from collection of distinct numbers ...Read MoreReal Time Analytics with Spring Application Development FrameworkSpring is the most popular application development framework for enterprise Java.Millions of developers use Spring to build simple, truly portable, fast and fle ...Read MorePath Setting in Java When an application is launched from command prompt Windows OS searches for the executable program in the current working directory. The prompt throws an error ...Read MoreFacebook | whatsapp|Github | Twitter | LinkedIn | Youtube| reddit About | Cookies-Policy | Disclaimer | Site Map | Contact

Call / Visit for New Batch

Services

Why Join Us

  • ➯ Free Demo Classes
  • ➯ No Registration Fee
  • ➯ Interview Questions
  • ➯ Study Materials
  • ➯ Softwares
  • ➯ Aptitude & Reasoning
  • ➯ Placement Assitance

Address

  • MyJava Training Institute ,
  • Plot No.243 , shop No 14 ,
  • Secnd Floor , Zone-II ,
  • M.P.Nagar , Bhopal,
  • Madhya Pradesh ( 462011 )
  • ☎  08871209400 , 7987028543
  • 🌐 www.myjava.in
FacebookGoogle +TwitterYouTube

MyJava - java Training Institute