MySQL的JDBC驱动
安装JDBC驱动:
解压缩mysql-connector-java-5.1.17.zip
将要使用的是mysql-connector-java-5.1.17-bin-g.jar和mysql-connector-java-5.1.17-bin.jar
配置
在C:\Program Files\Java目录下建立mysqlforjdbc子目录,进入该目录将mysql-connector-java-5.1.17-bin.jar到该目录下
进入C:\Program Files\Java\jdk1.5.0_04\lib目录将mysql-connector-java-5.1.17-bin-g.jar拷贝到该目录下
然后配置classpath,追加%JAVA_HOME%\lib\mysql-connector-java-5.1.17-bin-g.jar;C:\Program Files\Java\mysqlforjdbc\mysql-connector-java-5.1.17-bin.jar;到该环境变量中去
追加以后环境变量如下:
CLASSPATH=%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;C:\Program Files\Apache Software Foundation\Tomcat5.5\common\lib\servlet-api.jar;%JAVA_HOME%\lib\mysql-connector-java-5.1.17-bin-g.jar;C:\Program Files\Java\mysqlforjdbc\mysql-connector-java-5.1.17-bin.jar;
配置这个的目的是让java应用程序找到连接mysql的驱动.
查看并启动MySQL服务
在Windows XP下安装完MySQL后,它就已经自动启动服务了,并且在开始菜单中有其客户端的快捷方式连接
可以通过Windows的服务管理器查看。“开始”-“运行”,输入“services.msc”,回车。
弹出Windows的服务管理器,然后就可以看见服务名为“mysql”的服务项了,其右边标明“已启动”
在开始菜单-所有程序-MySQL-MySQL Server 5.1-MySQL Command Line Client用客户端的快捷方式连接
输入安装是设置的密码即可
6.数据库的使用
Mysql安装完毕以后,在开始菜单-所有程序-MySQL-MySQL Server 5.1-MySQL Command Line Client用客户端的快捷方式连接
输入安装时设置的密码
使用mysql的基本命令(在mysql命令行编辑每输入完命令后最后一定要有分号)
显示数据库:show databases;
使用数据库:use 数据库名;
建库
在mysql里建一个数据库first,以及在数据库里建一个表about
命令:create database first;
为数据库设置权限(用户和密码)
命令:grant all privileges on first.* to test@localhost identified by “123456”;
当你执行完这个命令以后,只要你再以用户名:test,密码:123456登录时你就只可以对first这个数据库操作,这样避开使用root
输入命令:use first;
使用first数据库;
在first库中建表
命令:create table about(id int(8) primary key,name varchar(10));
在表中假如数据:
命令:insert into about values('xyw1026','laojiang');
退出
命令:exit
JSP连接mysql
在C:\Program Files\Apache Software Foundation\Tomcat5.5\webapps目录下建立子目录myapp
进入C:\Program Files\Apache Software Foundation\Tomcat5.5\webapps\myapp目录下
用记事本编写一个文件保存为first.jsp
代码如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/softforum?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"
//first为你的数据库名
Connection conn= DriverManager.getConnection(url);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from first";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
在浏览器中输入:
http://127.0.0.1:8080/myapp/first.jsp
若出现:
id|num
0 |laojiang
数据库操作成功,恭喜你
万变不离其宗。。持久层怎么变也是JDBC,框架怎么新也是反射机制。。
今天刚好复习一下JDBC,顺便对MySql进行一个入门的学习。
环境:MySql 5.5 + Navicat for MySql 10.0.5 + MyEclipse 9.0
从MySql官方:http://www.mysql.com/ 下载了 mysql-connector-java-5.1.17-bin.jar
从MyEclipse的DB Browser中得到测试成功后的
驱动类:com.mysql.jdbc.Driver
链接URL:jdbc:mysql://localhost:3306/accp
准备的差不多了,实例就是 简单粗暴,直接有效 直接上代码。。
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
用户实体类:
- package com.accp.jdbc.entity;
- /**
- *
- * @author Maxpin on 2011-10-04
- *
- * 用户实体类
- */
- public class Userinfo {
- private int userid; // 编号
- private String loginid; // 用户名
- private String loginpwd; // 密码
- private String username; // 姓名
- /**
- * 构造方法
- */
- public Userinfo() {
- }
- /**
- * @param loginid
- * @param loginpwd
- * @param username
- */
- public Userinfo(String loginid, String loginpwd, String username) {
- this.loginid = loginid;
- this.loginpwd = loginpwd;
- this.username = username;
- }
- /**
- * @param userid
- * @param loginid
- * @param loginpwd
- * @param username
- */
- public Userinfo(int userid, String loginid, String loginpwd, String username) {
- this.userid = userid;
- this.loginid = loginid;
- this.loginpwd = loginpwd;
- this.username = username;
- }
- //getter & setter methods 略
Dao基类:包含了数据库链接、关闭、CRUD操作及MySql分页查询
- package com.accp.jdbc.base;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.List;
- import com.accp.jdbc.entity.Userinfo;
- /**
- *
- * @author Maxpin on 2011-10-04
- *
- * Dao基类:包含了数据库链接、关闭、CRUD操作及MySql分页查询
- */
- public class BaseDao {
- // 连接地址
- private static final String url = "jdbc:mysql://localhost:3306/accp";
- // 驱动类
- private static final String driverClass = "com.mysql.jdbc.Driver";
- // 用户名
- private static final String uname = "root";
- // 密码
- private static final String pwd = "admin";
- /**
- * 获取数据库连接
- *
- * @return 连接对象
- */
- protected static Connection getConnection() {
- Connection conn = null;
- try {
- Class.forName(driverClass);
- conn = DriverManager.getConnection(url, uname, pwd);
- } catch (ClassNotFoundException e) {
- System.out.println("找不到驱动类");
- } catch (SQLException e) {
- System.out.println("建立连接错误!");
- }
- return conn;
- }
- /**
- * 关闭数据库连接
- *
- * @param conn
- * 数据库连接
- * @param rs
- * 结果集
- * @param pstmt
- * 命令对象
- */
- public static void closeAll(Connection conn, ResultSet rs, Statement pstmt) {
- try {
- if (null != rs && !rs.isClosed()) {
- rs.close();
- rs = null;
- }
- } catch (SQLException e) {
- System.out.println("关闭结果集出错!");
- }
- try {
- if (null != pstmt && !pstmt.isClosed()) {
- pstmt.close();
- pstmt = null;
- }
- } catch (SQLException e) {
- System.out.println("关闭命令对象出错!");
- }
- try {
- if (null != conn && !conn.isClosed()) {
- conn.close();
- conn = null;
- }
- } catch (SQLException e) {
- System.out.println("关闭链接出错");
- }
- }
- /**
- * 保存指定用户信息
- *
- * @param user
- * 用户对象
- * @throws Exception
- * 抛出异常
- */
- public static void saveUserinfo(Userinfo user) throws Exception {
- if (null != user) {
- Connection conn = getConnection();
- PreparedStatement pstmt = null;
- String sql = "insert into USERINFO values(null,?,?,?)";
- try {
- pstmt = conn.prepareStatement(sql);
- pstmt.setString(1, user.getLoginid());
- pstmt.setString(2, user.getLoginpwd());
- pstmt.setString(3, user.getUsername());
- pstmt.executeUpdate();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- closeAll(conn, null, pstmt);
- }
- } else {
- throw new Exception("用户信息不能为空");
- }
- }
- /**
- * 删除指定用户信息
- *
- * @param user
- * 用户对象
- * @throws Exception
- * 抛出异常
- */
- public static void deleteUserinfo(Userinfo user) throws Exception {
- if (null != user) {
- Connection conn = getConnection();
- PreparedStatement pstmt = null;
- String sql = "delete from USERINFO where userid = ?";
- try {
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, user.getUserid());
- pstmt.executeUpdate();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- closeAll(conn, null, pstmt);
- }
- } else {
- throw new Exception("用户信息不能为空");
- }
- }
- /**
- * 更新指定用户信息
- *
- * @param user
- * 用户对象
- * @throws Exception
- * 抛出异常
- */
- public static void updateUserinfo(Userinfo user) throws Exception {
- if (null != user) {
- Connection conn = getConnection();
- PreparedStatement pstmt = null;
- String sql = "update USERINFO set loginid = ?,loginpwd = ?,username = ? where userid = ?";
- try {
- pstmt = conn.prepareStatement(sql);
- pstmt.setString(1, user.getLoginid());
- pstmt.setString(2, user.getLoginpwd());
- pstmt.setString(3, user.getUsername());
- pstmt.setInt(4, user.getUserid());
- pstmt.executeUpdate();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- closeAll(conn, null, pstmt);
- }
- } else {
- throw new Exception("用户信息不能为空");
- }
- }
- /**
- * 查询指定用户信息
- *
- * @param id
- * 用户编号
- * @return 用户对象
- * @throws Exception
- * 抛出异常
- */
- public static Userinfo queryUserinfo(int id) throws Exception {
- Userinfo user = null;
- Connection conn = getConnection();
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- String sql = "select * from USERINFO where userid = ?";
- try {
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, id);
- rs = pstmt.executeQuery();
- if (rs.next()) {
- user = new Userinfo(id, rs.getString(2), rs.getString(3),
- rs.getString(4));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- closeAll(conn, rs, pstmt);
- }
- return user;
- }
- /**
- * 分页查询用户信息列表
- *
- * @param currentPage
- * 要查询页码
- * @param pageSize
- * 每页显示条数
- * @return 用户对象集合
- * @throws Exception
- * 抛出异常
- */
- public static List<Userinfo> queryUserinfoList(int currentPage, int pageSize)
- throws Exception {
- // 计算当前页索引
- int pageIndex = (currentPage - 1) * pageSize;
- List<Userinfo> userList = new ArrayList<Userinfo>();
- Connection conn = getConnection();
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- // MySql分页可使用limit关键字:select * from tableName limit pageIndex,pageSize
- String sql = "select * from USERINFO limit ?,?";
- try {
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, pageIndex);
- pstmt.setInt(2, pageSize);
- rs = pstmt.executeQuery();
- while (rs.next()) {
- userList.add(new Userinfo(rs.getInt(1), rs.getString(2), rs
- .getString(3), rs.getString(4)));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- closeAll(conn, rs, pstmt);
- }
- return userList;
- }
- }
测试类:
- package com.accp.jdbc.test;
- import java.util.List;
- import com.accp.jdbc.base.BaseDao;
- import com.accp.jdbc.entity.Userinfo;
- /**
- *
- * @author Maxpin on 2011-10-04
- *
- * 测试类
- */
- public class Test {
- public static void main(String[] args) {
- try {
- /*
- * MySql中的初始数据:(编号、用户名、密码、姓名)
- * 1 admin 123123 管理员
- * 2 zhangsan 123123 张三
- * 3 lisi 123123 李四
- * 4 wangwu 123123 王五
- *
- */
- // 测试保存:赵六
- BaseDao.saveUserinfo(new Userinfo("zhaoliu", "123123", "赵六"));
- // 测试更新:赵六
- BaseDao.updateUserinfo(new Userinfo(5, "zhaoliu", "321321", "赵六2"));
- // 测试删除:王五
- BaseDao.deleteUserinfo(new Userinfo(4, null, null, null));
- // 测试查询:管理员
- Userinfo user = BaseDao.queryUserinfo(1);
- System.out.println(user.getUserid() + " " + user.getLoginid() + " "
- + user.getLoginpwd() + " " + user.getUsername());
- // 测试分页:查询第2页,每页2条。王五已被删除。
- List<Userinfo> userList = BaseDao.queryUserinfoList(2, 2);
- for (Userinfo u : userList) {
- System.out.println(u.getUserid() + " " + u.getLoginid() + " "
- + u.getLoginpwd() + " " + u.getUsername());
- }
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- }
---------------------------------------我是华丽的无所不在的分割线-------------------------------------------
MySql给我的感觉还可以,就是在安装完成后要配置一下my.ini
好在5.5提供了MySQLInstanceConfig.exe可以很方便的进行配置操作。
操作步骤我是参照的 http://www.duote.com/tech/1/2430.html#contentbody
另外:
MySql自增列的关键字是:AUTO_INCREMENT
插入数据时,可以选择对该列赋值为 null 即可。
MySql分页可使用limit关键字:select * from tableName limit pageIndex,pageSize

本文介绍如何使用JDBC连接MySQL数据库,并提供了一个完整的实战案例,包括用户实体类、DAO基类实现以及测试类验证。

109

被折叠的 条评论
为什么被折叠?



