JDBC和MyBatis的数据库连接代码

来源:互联网 发布:fedora25 yum 配置源 编辑:程序博客网 时间:2024/06/06 08:41

 

Mybatis连接数据库的方法:

1.编写mybatis-cfg.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>

   <environments default="development">

     <environment id="development">

     <transactionManager type="JDBC"></transactionManager>

     <dataSource type="POOLED">

     <property name="driver" value="com.mysql.jdbc.Driver"/>

     <property name="url" value="jdbc:mysql://localhost:3306/test"/>

     <property name="username" value="root"/>

     <property name="password" value="mysql"/>

     </dataSource>

     </environment>

   </environments>

  <mappers>

    <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>

  </mappers>

</configuration>

<?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>
   <environmentsdefault="development">
     <environment id="development">
     <transactionManager type="JDBC"></transactionManager>
     <dataSource type="POOLED">
     <property name="driver"value="com.mysql.jdbc.Driver"/>
     <property name="url"value="jdbc:mysql://localhost:3306/test"/>
     <property name="username"value="root"/>
     <property name="password"value="mysql"/>
     </dataSource>
     </environment>
   </environments>
  <mappers>
    <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>
  </mappers>
</configuration>

<?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>
   <environmentsdefault="development">
     <environment id="development">
     <transactionManager type="JDBC"></transactionManager>
     <dataSource type="POOLED">
     <property name="driver"value="com.mysql.jdbc.Driver"/>
     <property name="url"value="jdbc:mysql://localhost:3306/test"/>
     <property name="username"value="root"/>
     <property name="password"value="mysql"/>
     </dataSource>
     </environment>
   </environments>
  <mappers>
    <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>
  </mappers>
</configuration>

<?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>
   <environmentsdefault="development">
     <environment id="development">
     <transactionManager type="JDBC"></transactionManager>
     <dataSource type="POOLED">
     <property name="driver"value="com.mysql.jdbc.Driver"/>
     <property name="url"value="jdbc:mysql://localhost:3306/test"/>
     <property name="username"value="root"/>
     <property name="password"value="mysql"/>
     </dataSource>
     </environment>
   </environments>
  <mappers>
    <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>
  </mappers>
</configuration>
<?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>
   <environmentsdefault="development">
     <environment id="development">
     <transactionManager type="JDBC"></transactionManager>
     <dataSource type="POOLED">
     <property name="driver"value="com.mysql.jdbc.Driver"/>
     <property name="url"value="jdbc:mysql://localhost:3306/test"/>
     <property name="username"value="root"/>
     <property name="password"value="mysql"/>
     </dataSource>
     </environment>
   </environments>
  <mappers>
    <mapper resource="com/org/position/dao/employeeDaoMapper.xml"/>
  </mappers>
</configuration>
2.在impl中实现连接读取

public void test(){

String resource = "mybatis-cfg.xml";

Reader reader = null;

SqlSessionFactory ssf = null;

SqlSession session = null;

try{

reader = Resources.getResourceAsReader(resource);

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

ssf = builder.build(reader);

session = ssf.openSession();

int count = session.一系列操作

session.commit();

}catch{

}finally{

session.close();

}

}

JDBC连接数据库的方法:

1.建立一个BaseDao

  1. public  class BaseDao {   
  2.     /**  
  3.      * 获得连接  
  4.      * @return  
  5.      * @throws Exception  
  6.      */  
  7.     public Connection getConn()throws Exception{   
  8.            
  9.         /*          -***********************-mysql数据库-************************/  
  10.         Class.forName("com.mysql.jdbc.Driver");   
  11.         String uri="jdbc:mysql://localhost:3306/test?&useUnicode=true&characterEncoding=UTF-8";   
  12.         return DriverManager.getConnection(uri,"root","123");   
  13.            
  14.            
  15.         /*         -***********************sqlserver2005数据库-*******************  
  16.         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
  17.         String uri="jdbc:sqlserver://127.0.0.1:1433;DataBaseName=master";  
  18.         return DriverManager.getConnection(uri,"sa","123");*/  
  19.     }   
  20.        
  21.     /**  
  22.      * 关闭连接  
  23.      * @param rs  
  24.      * @param sm  
  25.      * @param conn  
  26.      */  
  27.     public void closeAll(ResultSet rs,Statement sm,Connection conn)throws Exception{   
  28.         if(rs!=null) rs.close();   
  29.         if(sm!=null) sm.close();   
  30.         if(conn!=null) conn.close();   
  31.     }   
  32.        
  33.     /**  
  34.      * 增加,删除,修改  
  35.      * @param sql  
  36.      * @param args  
  37.      * @return  
  38.      */  
  39.     public boolean executeUpdate(String sql,Object[] args){   
  40.         boolean flag=false;   
  41.         Connection conn=null;   
  42.         PreparedStatement sm=null;   
  43.         try {   
  44.             conn=this.getConn();   
  45.             sm=conn.prepareStatement(sql);   
  46.             if(conn != null){   
  47.                 for (int i = 0; i < args.length; i++) {   
  48.                     sm.setObject(i+1, args[i]);   
  49.                 }   
  50.             }   
  51.                
  52.             if(sm.executeUpdate() > 0){   
  53.                 flag = true;   
  54.             }   
  55.         } catch (Exception e) {   
  56.             // TODO: handle exception   
  57.         }finally{   
  58.             try {   
  59.                 this.closeAll(null, sm, conn);   
  60.             } catch (Exception e) {   
  61.                 // TODO Auto-generated catch block   
  62.                 e.printStackTrace();   
  63.             }   
  64.         }   
  65.         return flag;   
  66.     }   
  67.        
  68.     /**  
  69.      * 查询方法  
  70.      * @param sql  
  71.      * @param args  
  72.      * @return  
  73.      */  
  74.     public List executeQuery(String sql,Object[] args,Class clazz){   
  75.            
  76.         List list=new ArrayList();   
  77.         Connection conn = null;   
  78.         PreparedStatement sm = null;   
  79.         ResultSet rs = null;   
  80.         try {   
  81.             conn = this.getConn();   
  82.             sm = conn.prepareStatement(sql);   
  83.             if(args != null){   
  84.                 for (int i = 0; i < args.length; i++) {   
  85.                     sm.setObject(i+1, args[i]);   
  86.                 }   
  87.             }   
  88.             rs=sm.executeQuery();   
  89.             while(rs.next()){   
  90.             //通过反射得到一个对象   
  91.                 list.add(this.getObj(clazz, rs));   
  92.             }   
  93.                
  94.                
  95.         } catch (Exception e) {   
  96.             // TODO: handle exception   
  97.         }finally{   
  98.             try {   
  99.                 this.closeAll(null, sm, conn);   
  100.             } catch (Exception e) {   
  101.                 // TODO Auto-generated catch block   
  102.                 e.printStackTrace();   
  103.             }   
  104.         }   
  105.         return list;   
  106.     }   
  107.   
  108.     public static Object getObj(Class clazz,ResultSet rs)throws Exception{   
  109.         //所有的属性   
  110.         Field[] field= clazz.getDeclaredFields();   
  111.         Object info= clazz.newInstance();   
  112.         for (int i = 0; i < field.length; i++) {   
  113.             String name=field[i].getName().toUpperCase();   
  114.             //得到方法名   
  115.                 name="set"+name.charAt(0)+name.substring(1).toLowerCase();   
  116.             //得到类型   
  117.             Class  c=field[i].getType();   
  118.             //得到方法   
  119.             Method method= clazz.getMethod(name, c);   
  120.             //实现方法   
  121.             method.invoke(info, rs.getObject(i+1));   
  122.         }   
  123.         return info;   
  124.     }   
  125.        
  126.   
  127. }  

2.在实现类中编写的数据库读取

public void test(){

Connection conn = null;

PrepareStatement ps = null;

ResultSet rs = null;

try{

conn=this.getConn();

String sql = "";

ps = conn.createPrepareStatement();

rs = ps.executeQuery(sql);

while(rs.next()){

int id = rs.getInt("id");

String name = rs.getStrin("name");

syso("学号:"+id+"姓名:"+name)

}

ra.close();

}catch(){

}finally{

conn.close();

}

}

 

 

 

 

 

 

0 0
原创粉丝点击