<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html lang="en-US">
    <head>
        <title>Establishing a Connection (The Java&trade; Tutorials &gt;        
            JDBC(TM) Database Access &gt; JDBC Basics)
</title>

     <meta name="description" content="This JDBC Java tutorial describes how to use JDBC API to create, insert into, update, and query tables. You will also learn how to use simple and prepared statements, stored procedures and perform transactions" />
     <meta name="keywords" content="java programming, learn java, java sample code, jdbc, prepared statement, result set" />
        
<style type="text/css">
    .FigureCaption   { 
        margin-left: 1in; 
        margin-right: 1in; 
        font-family: sans-serif; 
        font-size: smaller; 
        text-align: justify;
    }
    #TopBar_bl {
        background: url(../../images/java_bar_bl.gif) 0 100% no-repeat;
        width: 100%;
        height: 60px;
    }
    #TopBar_br {
        background: url(../../images/java_bar_br.gif) 100% 100% no-repeat;
        width: 100%;
        height: 60px;
    }
    #TopBar_tl {
        background: url(../../images/java_bar_tl.gif) 0 0 no-repeat;
        width: 100%;
        height: 60px;
    }
    #TopBar_tr {
        background: url(../../images/java_bar_tr.gif) 100% 0 no-repeat;
        width: 100%;
        height: 60px;
    }
    #TopBar {
        background: #35556B url(../../images/java_bar.gif);
        margin: 10px 10px 0 10px;
        height:60px;
        min-width:700px;
        color: white;
        font-family: sans-serif; 
        font-weight: bold;
    }
    @media print {
        #BreadCrumbs, #Download {
            display: none;
        }
    }
    #TopBar_right {
        line-height: 14px;
        float: right;
        padding-top: 2px;
        padding-right: 30px;
        text-align: center;
    }
    @media print {
        #TopBar_right {
            display: none;
        }
    }
    #TopBar_right a {
        font-size: 12px;
        margin: 3px;
        padding: 0;
    }
    #TopBar a:visited, #TopBar a:link {
        color: white;
        text-decoration: none;
    }
    #TopBar a:hover, #TopBar a:active  {
        background-color: white;
        color: #35556B;
    }
    #BreadCrumbs {
        padding: 4px 5px 0.5em 0;
        font-family: sans-serif; 
        float: right;
    }
    #BreadCrumbs a {
        color: blue;
    }
    #BreadCrumbs a:visited, #BreadCrumbs a:link {
        text-decoration: none;
    }
    #BreadCrumbs a:hover, #BreadCrumbs a:active {
        text-decoration: underline;
    }
    #PageTitle {
        margin: 0 5px 0.5em 0;
        color: #F90000;
    }    
    #PageContent{
        margin: 0 5px 0 20px;
    }
    .LeftBar_shown {
        width: 13em;
        float: left;
        margin-left: 10px;
        margin-top: 4px;
        margin-bottom: 2em;
        margin-right: 10px;
    }
    @media print {
        .LeftBar_shown {
            display: none;
        }
    }
    .LeftBar_hidden {
        display: none;
    }
    #Footer {
        padding-top: 10px;
        padding-left: 10px;
        margin-right: 10px;
    }
    
    .footertext {
        font-size: 10px;
        font-family: sans-serif; 
        margin-top: 1px;
    }
    
    #Footer2 {
        padding-top: 10px;
        padding-left: 10px;
        margin-right: 10px;
    }
    .NavBit  {
        padding: 4px 5px 0.5em 0;
        font-family: sans-serif; 
    }
    @media print {
        .NavBit {
            display: none;
        }
    }
    #TagNotes {
        text-align: right;        
    }
    
    @media print {
        #TagNotes a:visited, #TagNotes a:link {
            color: #35556B;
            text-decoration: none;
        }
    }
    #Contents a, .NavBit a, #TagNotes a {
        color: blue
    }
    #TagNotes a:visited, #TagNotes a:link,
    #Contents a:visited, #Contents a:link,
    .NavBit a:visited, .NavBit a:link {
        text-decoration: none;
    }
    #TagNotes a:hover, #TagNotes a:active,   
    #Contents a:hover, #Contents a:active,   
    .NavBit a:hover, .NavBit a:active {  
        text-decoration: underline;
    }
    #Contents {
        float: left;
        font-family: sans-serif; 
    }
    @media print {
        #Contents {
            display: none;
        }
    }
    @media screen {
        div.PrintHeaders {
            display: none;
        }
    }
    .linkLESSON, .nolinkLESSON {
        margin-left: 0.5em;
        text-indent: -0.5em
    }
    .linkAHEAD, .nolinkAHEAD, .linkQUESTIONS, .nolinkQUESTIONS   {
        margin-left: 1.5em; 
        text-indent: -0.5em
    }
    .linkBHEAD, .nolinkBHEAD   {
        margin-left: 2.5em;
        text-indent: -0.5em
    }
    .linkCHEAD, .nolinkCHEAD   {
        margin-left: 3.5em;
        text-indent: -0.5em
    }
    .nolinkLESSON, .nolinkAHEAD, .nolinkBHEAD, .nolinkCHEAD,
    .nolinkQUESTIONS {
        font-weight: bold;
        color: #F90000;
    }
    .MainFlow_indented {
        margin-right: 10px;
        margin-left: 15em;
        margin-bottom: 2em;

    }
    .MainFlow_wide {
        margin-right: 10px;
        margin-left: 10px;
        margin-bottom: 2em;

    }
    @media print {
        .MainFlow_indented, .MainFlow_wide {
            padding-top: 0;
            margin-top: 10px;
            margin-right: 10px;
            margin-left: 0;
        }
    }
    h1, h2, h3, h4, h5 {
        color: #F90000;
        font-family: sans-serif;
    }

    h1 {
        font-weight: bold;
        font-size: 20px;
    }

    h2 {
        font-weight: bold;
        font-size: 17px;
    }

    h3 {
        font-weight: bold;
        font-size: 14px;
    }

    h4 {
        font-size: 15px;
    }

    h5 {
        font-size: 12px;
    }


    #ToggleLeft {
        display: none;
    }
    
    .note {
        margin: 0 30px 0px 30px;
    }
    
    .codeblock {
        margin: 0 30px 0px 30px;
    }

    /t

</style>
<script type="text/javascript">
    function leftBar() {
        var nameq = 'tutorial_showLeftBar='
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookieString = cookies[i];
            while (cookieString.charAt(0) == ' ') {
                cookieString = cookieString.substring(1, cookieString.length);
            }
            if (cookieString.indexOf(nameq) == 0) {
                cookieValue =  cookieString.substring(nameq.length,
                        cookieString.length);
                return cookieValue == 'yes';
            }
        }
        return true;
    }

    function showLeft(b) {
        var contents = document.getElementById("LeftBar");
        var main = document.getElementById("MainFlow");
        var toggle = document.getElementById("ToggleLeft");
        if (b) {
            contents.className = "LeftBar_shown";
            main.className = "MainFlow_indented";
            toggle.innerHTML = "Hide the TOC";
            document.cookie = 'tutorial_showLeftBar=yes; path=/';
        } else {
            contents.className = "LeftBar_hidden";
            main.className = "MainFlow_wide";
            toggle.innerHTML = "Show the TOC";
            document.cookie = 'tutorial_showLeftBar=no; path=/';
        }
    }

    function toggleLeft() {
        showLeft(document.getElementById("LeftBar").className ==
                "LeftBar_hidden");
        document.getElementById("ToggleLeft").blur();
    }

    function load() {
        showLeft(leftBar());
        document.getElementById("ToggleLeft").style.display="inline";
    }
    
</script>
<noscript> 
A browser with JavaScript enabled is required for this page to operate properly.
</noscript>

    </head>
<body onload="load()">
    <div id=TopBar> <div id=TopBar_tr> <div id=TopBar_tl> <div id=TopBar_br> <div id=TopBar_bl> 
                        <div id=TopBar_right> 
                            <a target="_blank"
                                href="http://java.sun.com/javase/6/download.jsp">Download
                                the JDK</a>
                            <br>
                            <a href="../../search.html" target="_blank">Search the
                                Tutorials</a>
                            <br>
                            <a href="javascript:toggleLeft()"
                                id="ToggleLeft">Hide the TOC</a>
                        </div>
                    </div> </div> </div> </div> </div>
    <div class=PrintHeaders>
        <b>Trail:</b> JDBC(TM) Database Access
        <br><b>Lesson:</b> JDBC Basics
    </div>

    <div id=LeftBar class=LeftBar_shown>
        <div id=Contents>
            <div class="linkLESSON"><a href="index.html">JDBC Basics</a></div>
<div class="linkAHEAD"><a href="gettingstarted.html">Getting Started</a></div>
<div class="linkAHEAD"><a href="processingsqlstatements.html">Processing SQL Statements with JDBC</a></div>
<div class="nolinkAHEAD">Establishing a Connection</div>
<div class="linkAHEAD"><a href="sqldatasources.html">Connecting with DataSource Objects</a></div>
<div class="linkAHEAD"><a href="sqlexception.html">Handling SQLExceptions</a></div>
<div class="linkAHEAD"><a href="tables.html">Setting Up Tables</a></div>
<div class="linkAHEAD"><a href="retrieving.html">Retrieving and Modifying Values from Result Sets</a></div>
<div class="linkAHEAD"><a href="prepared.html">Using Prepared Statements</a></div>
<div class="linkAHEAD"><a href="transactions.html">Using Transactions</a></div>
<div class="linkAHEAD"><a href="rowset.html">Using RowSet Objects</a></div>
<div class="linkAHEAD"><a href="jdbcrowset.html">Using JdbcRowSet Objects</a></div>
<div class="linkAHEAD"><a href="cachedrowset.html">Using CachedRowSetObjects</a></div>
<div class="linkAHEAD"><a href="joinrowset.html">Using JoinRowSet Objects</a></div>
<div class="linkAHEAD"><a href="filteredrowset.html">Using FilteredRowSet Objects</a></div>
<div class="linkAHEAD"><a href="webrowset.html">Using WebRowSet Objects</a></div>
<div class="linkAHEAD"><a href="sqltypes.html">Using Advanced Data Types</a></div>
<div class="linkAHEAD"><a href="blob.html">Using Large Objects</a></div>
<div class="linkAHEAD"><a href="sqlxml.html">Using SQLXML Objects</a></div>
<div class="linkAHEAD"><a href="array.html">Using Array Objects</a></div>
<div class="linkAHEAD"><a href="distinct.html">Using DISTINCT Data Type</a></div>
<div class="linkAHEAD"><a href="sqlstructured.html">Using Structured Objects</a></div>
<div class="linkAHEAD"><a href="sqlcustommapping.html">Using Customized Type Mappings</a></div>
<div class="linkAHEAD"><a href="sqldatalink.html">Using Datalink Objects</a></div>
<div class="linkAHEAD"><a href="sqlrowid.html">Using RowId Objects</a></div>
<div class="linkAHEAD"><a href="storedprocedures.html">Using Stored Procedures</a></div>
<div class="linkAHEAD"><a href="jdbcswing.html">Using JDBC with GUI API</a></div>
</div>
    </div>
    <div id=MainFlow class=MainFlow_indented>
            <span id=BreadCrumbs>
                <a href=../../index.html target=_top>Home Page</a>
                &gt;
                <a href=../index.html target=_top>JDBC(TM) Database Access</a>
                &gt;
                <a href=index.html target=_top>JDBC Basics</a>
            </span>
            <div class=NavBit>
                <a target=_top href=processingsqlstatements.html>&laquo;&nbsp;Previous</a>&nbsp;&bull;&nbsp;<a target=_top href=../TOC.html>Trail</a>&nbsp;&bull;&nbsp;<a target=_top href=sqldatasources.html>Next&nbsp;&raquo;</a>
            </div>
            <div id=PageTitle><h1>Establishing a Connection</h1></div>
            <div id=PageContent>
<p>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:</p>

<ul>
<li><p><code>DriverManager</code>: 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.</p>

<li><p><code>DataSource</code>: This interface is preferred over <code>DriverManager</code> because it allows details about the underlying data source to be transparent to your application. A <code>DataSource</code> object's properties are set so that it represents a particular data source. See <a href="sqldatasources.html">Connecting with DataSource Objects</a> for more information. For more information about developing applications with the <code>DataSource</code> class, see the latest <em><a href="http://download.oracle.com/javaee/6/tutorial/doc/">The Java EE Tutorial</a></em>.</li>

</ul>

<p><strong>Note</strong>: The samples in this tutorial use the <code>DriverManager</code> class instead of the <code>DataSource</code> class because it is easier to use and the samples do not require the features of the <code>DataSource</code> class.</p>

<p>This page covers the following topics:</p>

<ul>
  <li><a href="#drivermanager">Using the DriverManager Class</a></li>
  <li><a href="#db_connection_url">Specifying Database Connection URLs</a></li>
</ul>

<!-- *************************************** -->

<h2><a name="drivermanager">Using the DriverManager Class</a></h2>

<p>Connecting to your DBMS with the <code>DriverManager</code> class involves calling the method <code>DriverManager.getConnection</code>. The following method, <code><a href="gettingstarted.html">JDBCTutorialUtilities.getConnection</a></code>, establishes a database connection:</p>

<div class="codeblock"><pre>
  public Connection getConnection() throws SQLException {
    Connection conn = null;
    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);

    if (this.dbms.equals("mysql")) {
      conn = DriverManager.
        getConnection("jdbc:" + this.dbms + "://" + this.serverName +
                      ":" + this.portNumber + "/", connectionProps);
    } else if (this.dbms.equals("derby")) {
      conn = DriverManager.
        getConnection("jdbc:" + this.dbms + ":" + this.dbName + ";create=true", connectionProps);
    }
    System.out.println("Connected to database");
    return conn;
  }

</pre></div>

<p>The method <code>DriverManager.getConnection</code> establishes a database connection. This method requires a database URL, which varies depending on your DBMS. The following are some examples of database URLs:</p>

<ol>
  <li><p>MySQL: <code>jdbc:mysql://localhost:3306/</code>, where <code>localhost</code> is the name of the server hosting your database, and <code>3306</code> is the port number</p></li>
  <li><p>Java DB: <code>jdbc:derby:<em>testdb</em>;create=true</code>, where <code><em>testdb</em></code> is the name of the database to connect to, and <code>create=true</code> instructs the DBMS to create the database.</p>
  <p><strong>Note</strong>: This URL establishes a database connection with the Java DB Embedded Driver. Java DB also includes a Network Client Driver, which uses a different URL.</p>
  </li>
</ol>

<p>This method specifies the user name and password required to access the DBMS with a <code>Properties</code> object.</p>

<p><strong>Note</strong>:</p>

<ul>
  <li><p>Typically, in the database URL, you also specify the name of an existing database to which you want to connect. For example, the URL <code>jdbc:mysql://localhost:3306/mysql</code> represents the database URL for the MySQL database named <code>mysql</code>. The samples in this tutorial use a URL that does not specify a specific database because the samples create a new database.</p></li>

  <li><p>In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method <code>Class.forName</code>. This methods required an object of type <code>java.sql.Driver</code>. Each JDBC driver contains one or more classes that implements the interface <code>java.sql.Driver</code>. The drivers for Java DB are <code>org.apache.derby.jdbc.EmbeddedDriver</code> and <code>org.apache.derby.jdbc.ClientDriver</code>, and the one for MySQL Connector/J is <code>com.mysql.jdbc.Driver</code>. See the documentation of your DBMS driver to obtain the name of the class that implements the interface <code>java.sql.Driver</code>.</p>

  <p>Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method <code>Class.forName</code>.)</p></li>
</ul>

<p>The method returns a <code>Connection</code> object, which represents a connection with the DBMS or a specific database. Query the database through this object.</p>

<!-- *************************************** -->

<h2><a name="db_connection_url">Specifying Database Connection URLs</a></h2>

<p>A database connection URL is a string that your DBMS JDBC driver uses to connect to a database. It can contain information such as where to search for the database, the name of the database to connect to, and configuration properties. The exact syntax of a database connection URL is specified by your DBMS.</p>

<h3>Java DB Database Connection URLs</h3>

<p>The following is the database connection URL syntax for Java DB:</p>

<div class="codeblock"><pre>
jdbc:derby:[<em>subsubprotocol</em>:][<em>databaseName</em>][;<em>attribute</em>=<em>value</em>]*
</pre></div>

<ul>
  <li><code><em>subsubprotocol</em></code> specifies where Java DB should search for the database, either in a directory, in memory, in a class path, or in a JAR file. It is typically omitted.</li>

  <li><code><em>databaseName</em></code> is the name of the database to connect to.</lI>

  <li><code><em>attribute</em>=<em>value</em></code> represents an optional, semicolon-separated list of attributes. These attributes enable you to instruct Java DB to perform various tasks, including the following:
    <ul>
      <li>Create the database specified in the connection URL.</li>
      <li>Encrypt the database specified in the connection URL.</li>
      <li>Specify directories to store logging and trace information.</li>
      <li>Specify a user name and password to connect to the database.</li>
    </ul>
  </li>
</ul>

<p>See <em>Java DB Developer's Guide</em> and <em>Java DB Reference Manual</em> from <a href="http://download.oracle.com/javadb/">Java DB Technical Documentation</a> for more information.</p>

<h3>MySQL Connector/J Database URL</h3>

<p>The following is the database connection URL syntax for MySQL Connector/J:</p>

<div class="codeblock"><pre>
jdbc:mysql://[<em>host</em>][,<em>failoverhost</em>...][:<em>port</em>]/[<em>database</em>][?<em>propertyName1</em>][=<em>propertyValue1</em>][&amp;<em>propertyName2</em>][=<em>propertyValue2</em>]...
</pre></div>

<ul>
  <li><code><em>host</em>:<em>port</em></code> is the host name and port number of the computer hosting your database. If not specified, the default values of <code><em>host</em></code> and <code><em>port</em></code> are 127.0.0.1 and 3306, respectively.</li>

  <li><code><em>database</em></code> is the name of the database to connect to. If not specified, a connection is made with no default database.</li>

  <li><code><em>failover</em></code> is the name of a standby database (MySQL Connector/J supports failover).</li>

  <li><code><em>propertyName</em>=<em>propertyValue</em></code> represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.</li>
</ul>

<p>See <a href="http://dev.mysql.com/doc/"><em>MySQL Reference Manual</em></a> for more information.</p>

        </div>
        <div class=NavBit>
            <a target=_top href=processingsqlstatements.html>&laquo; Previous</a>
            &bull;
            <a target=_top href=../TOC.html>Trail</a>
            &bull;
            <a target=_top href=sqldatasources.html>Next &raquo;</a>
        </div>
    </div>
    <div id=Footer2>
<hr>
<div id=TagNotes>
    <p class="footertext">Problems with the examples? Try <a target="_blank"
        href=../../information/run-examples.html>Compiling and Running
        the Examples: FAQs</a>.
    <br>
    Complaints? Compliments? Suggestions? <a target="_blank"
        href="http://download.oracle.com/javase/feedback.html">Give
    us your feedback</a>.
    </p>
</div> 

<div id=Footer>
<p class="footertext"><a name="license_info">Your use of this</a> page and all the material on pages under &quot;The Java Tutorials&quot; banner,
and all the material on pages under &quot;The Java Tutorials&quot; banner is subject to the <a href="../../information/license.html">Java SE Tutorial Copyright
and License</a>.
Additionally, any example code contained in any of these Java
Tutorials pages is licensed under the
<a href="http://developers.sun.com/license/berkeley_license.html">Code
Sample License</a>.
</p>
<table border="0" cellspacing="0" cellpadding="5" summary="">
    <tr>
         <td headers="h1" width="20%">
	 <table width="100%" border="0" cellspacing="0" cellpadding="5">
            <tr>
              <td headers="h1" align="center"><img id=duke src=../../images/DukeWave.gif width=55 height=55 alt="duke image"></td>
              <td headers="h2" align="left" valign="middle"><img id=oracle src=../../images/logo_oracle_footer.gif width=100 height=29 alt="Oracle logo"></td>
           </tr>
          </table>
          </td>

          <td width="55%" valign="middle" align="center">
		<p class="footertext"><a href="http://www.oracle.com/us/corporate/index.html">About Oracle</a> | <a href="http://www.oracle.com/technology/index.html">Oracle Technology Network</a> | <a href="https://www.samplecode.oracle.com/servlets/CompulsoryClickThrough?type=TermsOfService">Terms of Service</a></p> 
	 </td>
          <td width="25%" valign="middle" align="right">
      		<p class="footertext">Copyright &copy; 1995, 2011 Oracle and/or its affiliates. All rights reserved.</p>
	 </td>
     </tr>     
</table>
</div>
    </div>
    <div class=PrintHeaders>
        <b>Previous page:</b> Processing SQL Statements with JDBC
        <br><b>Next page:</b> Connecting with DataSource Objects
    </div>

<!-- Start SiteCatalyst code   -->
<script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code_download.js"></script>
<script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code.js"></script>
<noscript> 
A browser with JavaScript enabled is required for this page to operate properly.
</noscript>
 
<!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** -->
<!--  Below code will send the info to Omniture server -->
<script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script>

 
<!-- End SiteCatalyst code -->

</body>
</html> 
