实例:简单的JDBC复习+MySql入门学习

18 篇文章 0 订阅
7 篇文章 0 订阅

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

 

准备的差不多了,实例就是 简单粗暴,直接有效 直接上代码。。

 

---------------------------------------我是华丽的无所不在的分割线-------------------------------------------

 

 

用户实体类:

Java代码   收藏代码
  1. package com.accp.jdbc.entity;  
  2.   
  3. /** 
  4.  *  
  5.  * @author Maxpin on 2011-10-04 
  6.  *  
  7.  *         用户实体类 
  8.  */  
  9. public class Userinfo {  
  10.     private int userid; // 编号  
  11.     private String loginid; // 用户名  
  12.     private String loginpwd; // 密码  
  13.     private String username; // 姓名  
  14.   
  15.     /** 
  16.      * 构造方法 
  17.      */  
  18.     public Userinfo() {  
  19.     }  
  20.   
  21.     /** 
  22.      * @param loginid 
  23.      * @param loginpwd 
  24.      * @param username 
  25.      */  
  26.     public Userinfo(String loginid, String loginpwd, String username) {  
  27.         this.loginid = loginid;  
  28.         this.loginpwd = loginpwd;  
  29.         this.username = username;  
  30.     }  
  31.   
  32.     /** 
  33.      * @param userid 
  34.      * @param loginid 
  35.      * @param loginpwd 
  36.      * @param username 
  37.      */  
  38.     public Userinfo(int userid, String loginid, String loginpwd, String username) {  
  39.         this.userid = userid;  
  40.         this.loginid = loginid;  
  41.         this.loginpwd = loginpwd;  
  42.         this.username = username;  
  43.     }  
  44.   
  45.     //getter & setter methods 略   

 

 

Dao基类:包含了数据库链接、关闭、CRUD操作及MySql分页查询

Java代码   收藏代码
  1. package com.accp.jdbc.base;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8. import java.sql.Statement;  
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11.   
  12. import com.accp.jdbc.entity.Userinfo;  
  13.   
  14. /** 
  15.  *  
  16.  * @author Maxpin on 2011-10-04 
  17.  *  
  18.  *         Dao基类:包含了数据库链接、关闭、CRUD操作及MySql分页查询 
  19.  */  
  20. public class BaseDao {  
  21.   
  22.     // 连接地址  
  23.     private static final String url = "jdbc:mysql://localhost:3306/accp";  
  24.     // 驱动类  
  25.     private static final String driverClass = "com.mysql.jdbc.Driver";  
  26.     // 用户名  
  27.     private static final String uname = "root";  
  28.     // 密码  
  29.     private static final String pwd = "admin";  
  30.   
  31.     /** 
  32.      * 获取数据库连接 
  33.      *  
  34.      * @return 连接对象 
  35.      */  
  36.     protected static Connection getConnection() {  
  37.         Connection conn = null;  
  38.         try {  
  39.             Class.forName(driverClass);  
  40.             conn = DriverManager.getConnection(url, uname, pwd);  
  41.         } catch (ClassNotFoundException e) {  
  42.             System.out.println("找不到驱动类");  
  43.         } catch (SQLException e) {  
  44.             System.out.println("建立连接错误!");  
  45.         }  
  46.         return conn;  
  47.     }  
  48.   
  49.     /** 
  50.      * 关闭数据库连接 
  51.      *  
  52.      * @param conn 
  53.      *            数据库连接 
  54.      * @param rs 
  55.      *            结果集 
  56.      * @param pstmt 
  57.      *            命令对象 
  58.      */  
  59.     public static void closeAll(Connection conn, ResultSet rs, Statement pstmt) {  
  60.         try {  
  61.             if (null != rs && !rs.isClosed()) {  
  62.                 rs.close();  
  63.                 rs = null;  
  64.             }  
  65.         } catch (SQLException e) {  
  66.             System.out.println("关闭结果集出错!");  
  67.         }  
  68.         try {  
  69.             if (null != pstmt && !pstmt.isClosed()) {  
  70.                 pstmt.close();  
  71.                 pstmt = null;  
  72.             }  
  73.         } catch (SQLException e) {  
  74.             System.out.println("关闭命令对象出错!");  
  75.         }  
  76.         try {  
  77.             if (null != conn && !conn.isClosed()) {  
  78.                 conn.close();  
  79.                 conn = null;  
  80.             }  
  81.         } catch (SQLException e) {  
  82.             System.out.println("关闭链接出错");  
  83.         }  
  84.     }  
  85.   
  86.     /** 
  87.      * 保存指定用户信息 
  88.      *  
  89.      * @param user 
  90.      *            用户对象 
  91.      * @throws Exception 
  92.      *             抛出异常 
  93.      */  
  94.     public static void saveUserinfo(Userinfo user) throws Exception {  
  95.         if (null != user) {  
  96.             Connection conn = getConnection();  
  97.             PreparedStatement pstmt = null;  
  98.             String sql = "insert into USERINFO values(null,?,?,?)";  
  99.             try {  
  100.                 pstmt = conn.prepareStatement(sql);  
  101.                 pstmt.setString(1, user.getLoginid());  
  102.                 pstmt.setString(2, user.getLoginpwd());  
  103.                 pstmt.setString(3, user.getUsername());  
  104.                 pstmt.executeUpdate();  
  105.             } catch (SQLException e) {  
  106.                 e.printStackTrace();  
  107.             } finally {  
  108.                 closeAll(conn, null, pstmt);  
  109.             }  
  110.         } else {  
  111.             throw new Exception("用户信息不能为空");  
  112.         }  
  113.     }  
  114.   
  115.     /** 
  116.      * 删除指定用户信息 
  117.      *  
  118.      * @param user 
  119.      *            用户对象 
  120.      * @throws Exception 
  121.      *             抛出异常 
  122.      */  
  123.     public static void deleteUserinfo(Userinfo user) throws Exception {  
  124.         if (null != user) {  
  125.             Connection conn = getConnection();  
  126.             PreparedStatement pstmt = null;  
  127.             String sql = "delete from USERINFO where userid = ?";  
  128.             try {  
  129.                 pstmt = conn.prepareStatement(sql);  
  130.                 pstmt.setInt(1, user.getUserid());  
  131.                 pstmt.executeUpdate();  
  132.             } catch (SQLException e) {  
  133.                 e.printStackTrace();  
  134.             } finally {  
  135.                 closeAll(conn, null, pstmt);  
  136.             }  
  137.         } else {  
  138.             throw new Exception("用户信息不能为空");  
  139.         }  
  140.     }  
  141.   
  142.     /** 
  143.      * 更新指定用户信息 
  144.      *  
  145.      * @param user 
  146.      *            用户对象 
  147.      * @throws Exception 
  148.      *             抛出异常 
  149.      */  
  150.     public static void updateUserinfo(Userinfo user) throws Exception {  
  151.         if (null != user) {  
  152.             Connection conn = getConnection();  
  153.             PreparedStatement pstmt = null;  
  154.             String sql = "update USERINFO set loginid = ?,loginpwd = ?,username = ? where userid = ?";  
  155.             try {  
  156.                 pstmt = conn.prepareStatement(sql);  
  157.                 pstmt.setString(1, user.getLoginid());  
  158.                 pstmt.setString(2, user.getLoginpwd());  
  159.                 pstmt.setString(3, user.getUsername());  
  160.                 pstmt.setInt(4, user.getUserid());  
  161.                 pstmt.executeUpdate();  
  162.             } catch (SQLException e) {  
  163.                 e.printStackTrace();  
  164.             } finally {  
  165.                 closeAll(conn, null, pstmt);  
  166.             }  
  167.         } else {  
  168.             throw new Exception("用户信息不能为空");  
  169.         }  
  170.     }  
  171.   
  172.     /** 
  173.      * 查询指定用户信息 
  174.      *  
  175.      * @param id 
  176.      *            用户编号 
  177.      * @return 用户对象 
  178.      * @throws Exception 
  179.      *             抛出异常 
  180.      */  
  181.     public static Userinfo queryUserinfo(int id) throws Exception {  
  182.         Userinfo user = null;  
  183.         Connection conn = getConnection();  
  184.         PreparedStatement pstmt = null;  
  185.         ResultSet rs = null;  
  186.         String sql = "select * from USERINFO where userid = ?";  
  187.         try {  
  188.             pstmt = conn.prepareStatement(sql);  
  189.             pstmt.setInt(1, id);  
  190.             rs = pstmt.executeQuery();  
  191.             if (rs.next()) {  
  192.                 user = new Userinfo(id, rs.getString(2), rs.getString(3),  
  193.                         rs.getString(4));  
  194.             }  
  195.         } catch (SQLException e) {  
  196.             e.printStackTrace();  
  197.         } finally {  
  198.             closeAll(conn, rs, pstmt);  
  199.         }  
  200.         return user;  
  201.     }  
  202.   
  203.     /** 
  204.      * 分页查询用户信息列表 
  205.      *  
  206.      * @param currentPage 
  207.      *            要查询页码 
  208.      * @param pageSize 
  209.      *            每页显示条数 
  210.      * @return 用户对象集合 
  211.      * @throws Exception 
  212.      *             抛出异常 
  213.      */  
  214.     public static List<Userinfo> queryUserinfoList(int currentPage, int pageSize)  
  215.             throws Exception {  
  216.         // 计算当前页索引  
  217.         int pageIndex = (currentPage - 1) * pageSize;  
  218.         List<Userinfo> userList = new ArrayList<Userinfo>();  
  219.         Connection conn = getConnection();  
  220.         PreparedStatement pstmt = null;  
  221.         ResultSet rs = null;  
  222.         // MySql分页可使用limit关键字:select * from tableName limit pageIndex,pageSize  
  223.         String sql = "select * from USERINFO limit ?,?";  
  224.         try {  
  225.             pstmt = conn.prepareStatement(sql);  
  226.             pstmt.setInt(1, pageIndex);  
  227.             pstmt.setInt(2, pageSize);  
  228.             rs = pstmt.executeQuery();  
  229.             while (rs.next()) {  
  230.                 userList.add(new Userinfo(rs.getInt(1), rs.getString(2), rs  
  231.                         .getString(3), rs.getString(4)));  
  232.             }  
  233.         } catch (SQLException e) {  
  234.             e.printStackTrace();  
  235.         } finally {  
  236.             closeAll(conn, rs, pstmt);  
  237.         }  
  238.         return userList;  
  239.     }  
  240.   
  241. }  

 

 

测试类:

 

Java代码   收藏代码
  1. package com.accp.jdbc.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.accp.jdbc.base.BaseDao;  
  6. import com.accp.jdbc.entity.Userinfo;  
  7.   
  8. /** 
  9.  *  
  10.  * @author Maxpin on 2011-10-04 
  11.  *  
  12.  *         测试类 
  13.  */  
  14. public class Test {  
  15.   
  16.     public static void main(String[] args) {  
  17.         try {  
  18.               
  19.             /* 
  20.              * MySql中的初始数据:(编号、用户名、密码、姓名) 
  21.              * 1 admin      123123  管理员 
  22.              * 2 zhangsan   123123  张三 
  23.              * 3 lisi       123123  李四 
  24.              * 4 wangwu     123123   王五 
  25.              *  
  26.              */  
  27.               
  28.             // 测试保存:赵六  
  29.             BaseDao.saveUserinfo(new Userinfo("zhaoliu""123123""赵六"));  
  30.             // 测试更新:赵六  
  31.             BaseDao.updateUserinfo(new Userinfo(5"zhaoliu""321321""赵六2"));  
  32.             // 测试删除:王五  
  33.             BaseDao.deleteUserinfo(new Userinfo(4nullnullnull));  
  34.             // 测试查询:管理员  
  35.             Userinfo user = BaseDao.queryUserinfo(1);  
  36.             System.out.println(user.getUserid() + " " + user.getLoginid() + " "  
  37.                     + user.getLoginpwd() + " " + user.getUsername());  
  38.             // 测试分页:查询第2页,每页2条。王五已被删除。  
  39.             List<Userinfo> userList = BaseDao.queryUserinfoList(22);  
  40.             for (Userinfo u : userList) {  
  41.                 System.out.println(u.getUserid() + " " + u.getLoginid() + " "  
  42.                         + u.getLoginpwd() + " " + u.getUsername());  
  43.             }  
  44.         } catch (Exception e) {  
  45.             System.out.println(e.getMessage());  
  46.         }  
  47.     }  
  48.   
  49. }  

 

---------------------------------------我是华丽的无所不在的分割线-------------------------------------------

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值