JSP与Mysql数据库的连接

发表于:2007-07-04来源:作者:点击数: 标签:
首先说明一下,我的 tomcat 5.0装在这里:E:\Program Files\Apache Software Foundation\ Tomcat 5.0,用的Mysql版本是: mysql -5.0.2-alpha-essential-win.msi 先将此 mysqldriver.jar 驱动文件放在:E:\Program Files\Apache Software Foundation\Tomcat 5
首先说明一下,我的tomcat 5.0装在这里:E:\Program Files\Apache Software

Foundation\Tomcat 5.0,用的Mysql版本是:mysql-5.0.2-alpha-essential-win.msi

先将此 mysqldriver.jar 驱动文件放在:E:\Program Files\Apache Software Foundation\Tomcat

5.0\common\lib下面,然后将这些内容:E:\Program Files\Apache Software Foundation\Tomcat 5.0

\common\lib\mysqldriver.jar 加到 classpath 环境变量中。

二、编写连接Mysql的 MySQLExample.java 文件,内容如下:

import java.sql.*;

public class MySQLExample{
public static void main(String args[]){
String serverName = "localhost";
try{
Class.forName("com.mysql.jdbc.Driver");//注册driver
String url = "jdbc:mysql://localhost:3306/pwoa";
Connection conn = DriverManager.getConnection(url,"root","1234");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from stud");
while(rs.next()){
System.out.print("name: "+rs.getString(1));
System.out.print("\tsex: "+rs.getString(2));
System.out.println("\tscore: "+rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

注意:这 Connection conn = DriverManager.getConnection(url,"root","1234"); 句中的1234是

你安装Mysql时的密码。若你的密码不是1234的话,这里需要改一下。

三、打开Mysql,建数据库pwoa,在建表stud,插入以下八条记录。语句如下所示:

create database pwoa;
use pwoa;
create table stud(
name varchar(8),
sex varchar(8),
score varchar(2)
);
insert into stud values ('Tom','m','88');
insert into stud values ('Jack','m','98');
insert into stud values ('Henry','m','74');
insert into stud values ('Mary','f','65');
insert into stud values ('Brook','f','69');
insert into stud values ('Stony','f','100');
insert into stud values ('Stone','m','89');
insert into stud values ('Max','f','82');

四、编译MySQLExample.java 文件,然后运行 MySQLExample.java文件,命令如下:

javac MySQLExample.java

java MySQLExample

五、此时就会看到这些内容,如下:

name: Tom sex: m score: 88
name: Jack sex: m score: 98
name: Henry sex: m score: 74
name: Mary sex: f score: 65
name: Brook sex: f score: 69
name: Stony sex: f score: 10
name: Stone sex: m score: 89
name: Max sex: f score: 82


写的有点乱,若那里有错误,请指出来。

原文转自:http://www.ltesting.net