免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 911 | 回复: 0
打印 上一主题 下一主题

Connecting to a MySQL Database [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-09-03 18:10 |只看该作者 |倒序浏览

Connecting to a MySQL Database using Connector/J JDBC Driver
by
Faisal Khan
.
file:///C:/Documents%20and%20Settings/jink/Desktop/Connecting%20to%20a%20MySQL%20Database%20using%20Connector-J%20JDBC%20Driver_files/jug.gif
Overview
In this tutorial following topics will be covered:

  • What are Database URLs in JDBC?
  • Why and how to specify a JDBC Driver name?
  • How to create a connection to a Database?
  • An example on how to connect to a MySQL Database?

Note: This tutorial assumes you've correctly setup MySQL database and Connector/J JDBC driver. If not then consult "
Installing and Configuring MySQL Database and Connector/J JDBC Driver on Microsoft Windows
".
file:///C:/Documents%20and%20Settings/jink/Desktop/Connecting%20to%20a%20MySQL%20Database%20using%20Connector-J%20JDBC%20Driver_files/jug.gif
What are Database URLs in JDBC?
URL stands for "Uniform Resource Locator". You will be familiar with HTTP URLs that you normally use to access a web site e.g. http://www.stardeveloper.com. URLs are used to identify a resource using a unique name.
Same goes for database URLs in JDBC. JDBC requires that all database connection strings should be represented by URLs. The URLs used in JDBC have following structure:
jdbc:subprotocol:subname
In HTTP you begin a URL with the protocol name i.e. http:, similarly in JDBC driver URLs, you start the URL with protocol name i.e. jdbc:. Next subprotocol represents the database you want to connect to e.g. mysql, oracle, odbc etc. While subname provides additional information on how and where to connect.
Tip: If you are familiar with ASP/ASP.NET, a database URL in JDBC is quite similar to a connection string used in an ASP environment to connect to a database.
Examples of Database URLs
Following are some examples of JDBC database URLs:

  • jdbc:odbc:dsn_name;UID=your_uid;PWD=your_pwd - JDBC-ODBC Bridge Driver URL.
  • jdbc:oracle:thin:@machine_name:port_number:instance_name - Orace Type 4 JDBC Driver.
  • jdbc:mysql://host_name:port/dbname - MySQL Connector/J JDBC Driver.

file:///C:/Documents%20and%20Settings/jink/Desktop/Connecting%20to%20a%20MySQL%20Database%20using%20Connector-J%20JDBC%20Driver_files/jug.gif
Why and how to specify a JDBC Driver name?
Next thing you need to know besides the database URL is the full class name of your JDBC driver e.g. com.mysql.jdbc.Driver in case of MySQL Connector/J JDBC driver. The name of the driver is a requirement and is not optional.
Note: In ASP/ASP.NET both database URL and driver name are part of a single connection string, while Java separates them for greater flexibility.
You can tell JVM about what driver/s to use by using one of the following methods:

  • To load the the driver/s at JVM startup, specify the driver/s in jdbc.drivers system property like this:
    java -Djdbc.drivers=com.mysql.jdbc.Driver YourJavaProgram
  • To explicitly load the driver, use Class.forName() method in your code like this:
    Class.forName("com.mysql.jdbc.Driver").newInstance();

Note: In above examples, "com.mysql.jdbc.Driver" is the name of the JDBC driver that you want to load.
The example discussed in this tutorial makes use of the second option discussed above.
file:///C:/Documents%20and%20Settings/jink/Desktop/Connecting%20to%20a%20MySQL%20Database%20using%20Connector-J%20JDBC%20Driver_files/jug.gif
How to create a connection to a Database?
To create a connection to a database, you will have to use java.sql.DriverManager's getConnection() method. This method takes as an argument the database URL (that we discussed earlier) you want to connect to. It then internally finds the appropriate driver which has been loaded in the JVM and then delegates the work of creating the connection to that driver.
file:///C:/Documents%20and%20Settings/jink/Desktop/Connecting%20to%20a%20MySQL%20Database%20using%20Connector-J%20JDBC%20Driver_files/jug.gif
An example on how to connect to a MySQL Database?
After learning the theory behind connecting to a database, we'll now move on to create a Java program which will connect to a MySQL database running on your local system.
Note: This tutorial assumes you've correctly setup MySQL database and Connector/J JDBC driver. If not then consult "
Installing and Configuring MySQL Database and Connector/J JDBC Driver on Microsoft Windows
".
JdbcExample2.java
Create a new Java source file and save it as JdbcExample2.java. Copy/paste following code in it:
package com.stardeveloper.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcExample2 {
  public static void main(String args[]) {
    Connection con = null;
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql:///test",
        "root", "secret");
      if(!con.isClosed())
        System.out.println("Successfully connected to " +
          "MySQL server using TCP/IP...");
    } catch(Exception e) {
      System.err.println("Exception: " + e.getMessage());
    } finally {
      try {
        if(con != null)
          con.close();
      } catch(SQLException e) {}
    }
  }
}
Explanation
Above Java program tries to connect to "test" database installed on your local MySQL server. "test" database is installed on all MySQL servers by default so that is why I am using this database to connect to, otherwise as far as this tutorial is concerned, it won't be accessing any tables in that database.

( 1 Remaining )
Next

Comments/Questions ( Threads: 16, Comments: 34 )

  • Connection refused problem
    ( 0 Replies ).

  • 2 connections with 1 driver instance...
    ( 0 Replies ).

  • Load driver exception using Connector/J
    ( 1 Replies ).

  • Solution 1 & 2 to
    ( 0 Replies ).

  • How to connect MS-Access and My-Sql with JSP and Tomcat 5.0
    ( 0 Replies ).

  • Please Resolve the Exception
    ( 1 Replies ).

  • Problem Solved.
    ( 0 Replies ).

  • Class not found error
    ( 1 Replies ).

  • how to load the driver for mysql using jdbc
    ( 4 Replies ).

  • how to connect remote MYSQL using java
    ( 3 Replies ).

  • Exception in using the driver
    ( 0 Replies ).

  • yet another obstacle during run
    ( 0 Replies ).

  • Exceptions during run of example2
    ( 5 Replies ).

  • Connection problem under Debian (Gnu)-Linux
    ( 0 Replies ).

  • problem in running example 2
    ( 1 Replies ).

  • About JSP and Mysql (Help me please)
    ( 2 Replies ).

    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/29515/showart_373550.html
  • 您需要登录后才可以回帖 登录 | 注册

    本版积分规则 发表回复

      

    北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
    未成年举报专区
    中国互联网协会会员  联系我们:huangweiwei@itpub.net
    感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

    清除 Cookies - ChinaUnix - Archiver - WAP - TOP