myeclipse连接数据库建立web工程简单测试访问成功例子.doc
文本预览下载声明
Myeclipse 连接数据库 测试查询 成功
一,建立数据库
首先建立数据库,在数据库里建立表格,填充内容。
以navicat for MySql为例
二,建立web工程
三,连接数据库
1,打开Database。
点击window窗口 点击Open Perspective菜单中的MyEclipse Database Explorer
2,创建连接。
在空白处右击鼠标新建(即new)或者点击菜单栏中的快捷键(图二中向下的三角符号)新建
3,弹出Database Driver 菜单
4,选择连接方式。
在Driver template选项框中 选择MySql Connector/j
5,填写配置信息
1,在Driver name填写链接数据库的名称(这个可由自己喜好填写,建议最好和所做项目名称相关便于使用时 查找)
2,Connection URL用于填写连接要使用mysql数据库的地址(jdbc:mysql://[:3306]/)可改为(jdbc:mysql://localhost:3306/test),其中localhost表示的是连接本地数据库的意思,3306是表示连接mysql数据库的端口号(不同的数据库端口号也不相同)
3,User name 填写数据库用户名mysql默认的是root,
4,Password填写访问mysql数据库时的你所设置的访问密码
6, 添加驱动
点击Add JARs添加myeclipse连接mysql数据库的驱动文件(存放驱动的文件最好是英文目录,在测试时确定mysql数据库已经打开,否则测试不会成功),在这里添加的是mysql-connector-java-5.1.7-bin版本(可以在网上搜索下载、)
7,测试数据配置是否正确
点击Test Driver测试是否配置成功输入访问数据库密码
8,测试成功
测试连接mysql数据库成功,点击Finish完成创建连接。
9.连接数据库
右击你创建的连接点击Open another connection
输入mysql数据库密码就能看到所创建的数据库表
四,web工程添加驱动包
选中工程,右击-Build Path-Add External Archives
找到下载的驱动包,并打开打开之后,如图,则添加成功!五,访问数据库,测试
打开WebRoot-index.jsp,粘贴如下代码,并保存
把index.jsp中的代码改为如下:
%@ page contentType=text/html; charset=gb2312 %%@ page language=java %%@ page import=com.mysql.jdbc.Driver %%@ page import=java.sql.* %% //驱动程序名String driverName=com.mysql.jdbc.Driver;//数据库用户名String userName=root;//密码String userPasswd=123456;//数据库名String dbName=companysystem;//表名String tableName=admin;//联结字符串String url=jdbc:mysql://localhost/+dbName+?user=+userName+password=+userPasswd;
Class.forName(com.mysql.jdbc.Driver).newInstance();
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql=SELECT * FROM +tableName;
ResultSet rs = statement.executeQuery(sql);//获得数据结果集合ResultSetMetaData rmeta = rs.getMetaData();//确定数据集的列数,亦字段数int numColumns=rmeta.getColumnCount();//输出每一个数据值out.print(id);out.print(|);out.print(num);out.print(br);while(rs.next()) {out.print(rs.getString(1)+ );out.print(|);out.print(rs.getString(2));out.print(br);}
显示全部