jdbc-mysql的经典案例

package com.execlExport.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * DatabaseUtil 
 * 创建人: TanLiu
 * 时间: 2015-1-19 下午9:08:23
 * 作用: 
 */
public class DatabaseUtil {

 private final String Driver = "com.mysql.jdbc.Driver";
 private final String URL = "jdbc:mysql://localhost:3306/tmdest";
 private final String User = "root";
 private final String pwd ="123456";

 private Connection con = null;

 private PreparedStatement ps = null;
    public ResultSet rs=null;    
    /**
     *作用:获取对数据库的连接
     */
    public void getConnection(){
        try {
   Class.forName(Driver);
   con=DriverManager.getConnection(URL,User,pwd);
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }       
    }
    /**
     *作用:对数据的查询操作
     * @param sql
     * @param arr
     * @return 返回一个数据集rs
     */
    public ResultSet getQuery(String sql,String[] arr){
     getConnection();
     try {
   ps=con.prepareStatement(sql);
   if(arr!=null&&arr.length>0){
    for(int i=0;i<arr.length;i++){
     ps.setString(i+1, arr[i]);
    }
   }
   rs=ps.executeQuery();
  } catch (SQLException e) {

   e.printStackTrace();
  }finally{
   this.closeAll();
  }

     return rs;
    }

    /**
     *作用:用于对数据库的更新操作
     * @param sql
     * @param arr
     * @return row
     */
    public int getUpdate(String sql,String[] arr){
     int row=0;
     getConnection();
     try {
   ps=con.prepareStatement(sql);
   if(arr!=null&&arr.length>0){
    for(int i=0;i<arr.length;i++){
     ps.setString(i+1, arr[i]);
    }
   }
   row=ps.executeUpdate();
  } catch (SQLException e) {

   e.printStackTrace();
  }finally{
   this.closeAll();
  }
        return row;
    }

    /**
     *作用:对数库操作的关闭
     */
    private void closeAll(){

      try {
       if(rs!=null){
    rs.close();
       }
       if(ps!=null){
        ps.close();
       }
       if(con!=null){
        con.close();
       }
   } catch (SQLException e) {    
    e.printStackTrace();
   }
    }
}

package
com.execlExport.util;import java.sql.Connection;import
java.sql.DriverManager;import java.sql.PreparedStatement;import
java.sql.ResultSet;import j…

MyBatis的经典案例,MyBatis经典案例

    1.首先我们先了解Mybatis的一些jar包

美高梅电子游戏 1

美高梅电子游戏 ,    —和项目框架

     美高梅电子游戏 2

    2.接下来就看看mybatis的配置文件(mybatis-config.xml)

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
     <!-- 别名 -->
     <typeAliases >
     <package name="cn.happy.entity"/>
     </typeAliases>

    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc的事务 -->
            <transactionManager type="JDBC" />
            <!-- 使用自带的连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
                <property name="username" value="happy" />
                <property name="password" value="1" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 连接小配置 -->
        <mapper resource="cn/happy/dao/StudentDAO.xml" />
    </mappers>
</configuration>

 

    3.在dao层的小配置(StudentDAO.xml)

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.happy.dao">

    <!-- 添加 -->
    <insert id="insertStudent">
        insert into student(stuno,stuname,stuage,studate)
        values(ssm.nextval,#{stuname},#{stuage},#{studate})

        <selectKey keyProperty="stuno" resultType="int">
            select SSM.CURRVAL from dual
        </selectKey>
    </insert>
    <!-- 查询所有 -->
    <select id="findAll" resultType="Student">
        select * from student
    </select>

    <!-- 模糊查询 -->
    <select id="findAllLike" resultType="Student">
        <!-- 不管参数为什么都可以 -->
         <!--select * from student where stuname like concat('%',#{stuname},'%')--> 
          <!-- 字符串 -->
         <!--  select * from student where  stuname like '%${value}%' -->
         <!-- 对象 -->
         select * from student where  stuname like '%${stuname}%'
    </select>

    <!--删除学生 -->

    <delete id="delStudent">
        delete from student where stuno=#{id}<!-- #{id}随便写,起到一个占位的作用 -->
    </delete>

</mapper>

 

 

     4.entity层实体类(Student)

 

package cn.happy.entity;

import java.util.Date;

public class Student {

    private int stuno;
    private String stuname;
    private int stuage;
    private Date studate;
    public String toString() {
        return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
                + stuage + ", studate=" + studate + "]";
    }
    public int getStuno() {
        return stuno;
    }
    public void setStuno(int stuno) {
        this.stuno = stuno;
    }
    public String getStuname() {
        return stuname;
    }
    public void setStuname(String stuname) {
        this.stuname = stuname;
    }
    public int getStuage() {
        return stuage;
    }
    public void setStuage(int stuage) {
        this.stuage = stuage;
    }
    public Date getStudate() {
        return studate;
    }
    public void setStudate(Date studate) {
        this.studate = studate;
    }

}

 

 

   5.dao层(IStudentDAO)

 

package cn.happy.dao;

import java.io.IOException;
import java.util.List;

import cn.happy.entity.Student;

public interface IStudentDAO {

    /*
     * 添加学生信息
     */
    public int addStu(Student stu) throws IOException;

    /*
     * 查询所有
     */
    public List<Student> findAll() throws IOException;

    /*
     * 模糊查询
     */
    public List<Student> findAlllike(Student stu) throws IOException;

    /*
     * 模糊查询字符串
     */
    public List<Student> findAlllikebstuname(String stuname) throws IOException;

    /*
     * 删除
     */
    public int delStudent(int id) throws IOException;
}

 

 

   6.dao层下的impl层(IStudentDAOImpl)

 

package cn.happy.dao.impl;

import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import cn.happy.dao.IStudentDAO;
import cn.happy.entity.Student;
import cn.happy.util.MybatisUtil;

public class IStudentDAOImpl implements IStudentDAO{

    /*
     * session成员变量
     */
     SqlSession session;

    /*
     * 添加
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#addStu(cn.happy.entity.Student)
     */
    public int addStu(Student stu) throws IOException {
        //获取session 
        session = MybatisUtil.getSession();

        //添加insert
        int result = session.insert("insertStudent", stu);

        //添加事物
        session.commit();

        //关闭session
        session.close();
        return result;
    }

    /*
     * 查询所有
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#fandAll()
     */
    public List<Student> findAll() throws IOException {
         //获取session
         session = MybatisUtil.getSession();
         List<Student> list = session.selectList("findAll");
         //关闭session
         session.close();
         return list;
    }

    /*
     * 模糊查询
     * 1.参数为对象
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#findAll(cn.happy.entity.Student)
     */
    public List<Student> findAlllike(Student stu) throws IOException {
        //获取session
         session = MybatisUtil.getSession();
         List<Student> list = session.selectList("findAllLike",stu);
        //关闭session
         session.close();
         return list;
    }

    /*
     * 模糊查询
     * 2.参数为字符串
     * (non-Javadoc)
     * @see cn.happy.dao.IStudentDAO#findAll(cn.happy.entity.Student)
     */
    public List<Student> findAlllikebstuname(String stuname) throws IOException {
        //获取session
         session = MybatisUtil.getSession();
         System.out.println("222");
         List<Student> list = session.selectList("findAllLike",stuname);
         System.out.println("333");
        //关闭session
         session.close();
         return list;
    }

    /*
     * 删除
     */
    public int delStudent(int id) throws IOException {
         //获取session
         session = MybatisUtil.getSession();
         int result = session.delete("delStudent", id);
         session.commit();
         return result;
    }

}

 

 

      7.util层的工具类(MybatisUtil )

 

package cn.happy.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 工具类
 * @author Happy
 *
 */
public class MybatisUtil {
    private static String config="mybatis-config.xml";
    static Reader reader;
    static{
        try {
            reader= Resources.getResourceAsReader(config);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
    //提供一个可以获取到session的方法
    public static SqlSession getSession() throws IOException{

           // 1.1 openSession到底做了什么
           SqlSession session = factory.openSession();
           System.out.println("3333");
            return session;
    }
}

 

 

   8. 日志信息配置文件(log4j.properties)

 

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

//记录cn.happy.dao包下的信息
log4j.logger.cn.happy.dao=trace, stdout

 

 

       暂时就这么多了,如果想了解更多就记得多多关注吧!!!!

 

1.首先我们先了解Mybatis的一些jar包 —和项目框架
2.接下来就看看mybatis的配置文件( mybatis-config.xml ) ?xml…

Author

发表评论

电子邮件地址不会被公开。 必填项已用*标注

相关文章