posts - 495,  comments - 11,  trackbacks - 0

1.到http://www.mysql.com下载MySQL数据库服务器和驱动程序Jdbc driver for MySQL

2.安装MySQL数据库,本人下载的是安装版本的,所以直接点Setup.exe就可以了,当然也可以下载.zip解压版本的,不过解压后要设置下环境变量之类的,麻烦~~

3.设置驱动程序路径,本人下载的Jdbc driver for MySQL是mysql-connector-java-5.0.7-bin.jar,将它放到<MySQL_HOME>\,然后在系统环境变量中的classpath加入mysql-connector-java-5.0.7-bin.jar的路径,如我加入的是:C:\Program Files\MySQL\MySQL Server 5.0\mysql-connector-java-5.0.7-bin.jar,OK

4.创建数据库,组合键Win+R,输入cmd后回车,进入命令行模式,键入mysql -uroot -p你设置的密码

      create database mydb01;

      use mydb01;

      create table table1(CD int(8) primary key,NAME varchar(10));

      insert into table1 values(1,'name1');

      insert into table1 values(2,'name2');

      insert into table1 values(3,'name3');

      输入命令:select * from table1;如果见到以下内容,则说明数据库创建成功.

+------+-------+
| CD      | NAME     |
+------+-------+
|       1 | name1 |
|       2 | name2 |
|       3 | name3 |
+------+-------+

5.编写连接数据库的测试代码

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;

public class mysqltest {
       public static void main(String[] args) {
           try{
               Class.forName("com.mysql.jdbc.Driver").newInstance();
               String url ="jdbc:mysql://localhost:3306/mydb01";
               Connection conn= DriverManager.getConnection(url,"root","你设置的密码");
               Statement stmt=conn.createStatement();
               String sql="select * from table1";
               ResultSet rs=stmt.executeQuery(sql);

               while(rs.next()) {
                   System.out.print(rs.getInt("CD")+"\t");
                   System.out.println(rs.getString("NAME"));
               }

               System.out.println("Done");
               rs.close();
               stmt.close();
               conn.close();
            
          }catch(Exception e){
              e.printStackTrace();
          }
       }
}

6.再次进入命令行模式,测试一下是否连接成功

    javac mysqltest.java

    java    mysqltest

posted on 2007-08-04 09:24 jadmin 阅读(46) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: