白桦的天空

第一次的心动,永远的心痛!
  首页  :: 新随笔  :: 联系 :: 管理

JAVA连接MySQL数据库的例子

Posted on 2008-09-25 11:10  白桦的天空  阅读(3087)  评论(0编辑  收藏  举报
注意,在执行程序前已经在MySQL中的test数据库中建立了一个表pet,表的结构和内容如下:
代码
D:\>mysql
Welcome to the MySQL monitor.  Commands end with; or \g.
Your MySQL connection id is 70 to server version: 5.0.18-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> use test
Database changed
mysql> desc pet;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(20) | YES  |     | NULL    |       |
| owner   | varchar(20) | YES  |     | NULL    |       |
| species | varchar(20) | YES  |     | NULL    |       |
| sex     | char(1)     | YES  |     | NULL    |       |
| birth   | date        | YES  |     | NULL    |       |
| death   | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
6 rows in set (0.01 sec)

mysql> select * from pet;
+----------+--------+---------+------+------------+------------+
| name     | owner  | species | sex  | birth      | death      |
+----------+--------+---------+------+------------+------------+
| Fluffy   | Harold | cat     | f    | 1993-02-04 | 0000-00-00 |
| Claws    | Gwen   | cat     | m    | 1994-03-17 | 0000-00-00 |
| Buffy    | Harold | dog     | f    | 1989-05-13 | 0000-00-00 |
| Fang     | Benny  | dog     | m    | 1990-08-27 | 0000-00-00 |
| Bowser   | Diane  | dog     | m    | 1979-08-31 | 1995-07-29 |
| Chirpy   | Gwen   | bird    | f    | 1998-09-11 | 0000-00-00 |
| Whistler | Gwen   | bird    | NULL | 1997-12-09 | 0000-00-00 |
| Slim     | Benny  | snake   | m    | 1996-04-29 | NULL       |
| Puffball | Diane  | hamster | f    | 1999-03-30 | NULL       |
+----------+--------+---------+------+------------+------------+
9 rows in set (0.00 sec)

mysql>

JAVA程序的内容如下
代码
import java.sql.*;

public class SampleIntro
{
  public static void main(String[] args)
  {
    try
    {
      Connection conn;
      Statement stmt;
      ResultSet res;
      //加载Connector/J驱动
      //这一句也可写为:Class.forName("com.mysql.jdbc.Driver");
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      //建立到MySQL的连接
      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
                                         "root", "guapo");
      //执行SQL语句
      stmt = conn.createStatement();
      res = stmt.executeQuery("select * from pet");
      //处理结果集
      while (res.next())
      {
        String name = res.getString("name");
        System.out.println(name);
      }
      res.close();

    }
    catch (Exception ex)
    {
      System.out.println("Error : " + ex.toString());
    }
  }
}

下面是执行结果
代码
D:\>javac SampleIntro.java

D:\>java SampleIntro
Fluffy
Claws
Buffy
Fang
Bowser
Chirpy
Whistler
Slim
Puffball

D:\>