</pre>1、JDBC訪问方法</p><p></p><p>DBHelper类訪问数据库。Dao类写数据訪问,View类进行应用,初学实例图书管理系统。</p><p></p><pre class="java" name="code">package util;

import java.sql.Connection;
import java.sql.DriverManager; public class DBHelper {
private static Connection conn;
private static final String DBurl="jdbc:mysql://localhost:3306/db_book? useUnicode=true&characterEncoding=UTF-8";
private static final String DBuser="root";
private static final String DBpass="root";
private static final String DRIVER="com.mysql.jdbc.Driver"; static
{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO 自己主动生成的 catch 块
e.printStackTrace();
}
} private DBHelper()
{ } public static Connection getConnection() throws Exception
{
if(conn==null)
{
conn=DriverManager.getConnection(DBurl, DBuser, DBpass);
}
return conn; }
public static void closeConn()throws Exception
{
if(conn!=null)
{
conn.close();
}
}
}
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import util.StrUtil;
import model.Book; public class BookDao { public int addBook(Connection conn,Book bk) throws Exception
{
String sql="insert into t_book values(null,?,?,?,?,?,?)";
PreparedStatement psmt=conn.prepareStatement(sql);
psmt.setString(1, bk.getBookname());
psmt.setString(2, bk.getAuthor());
psmt.setString(3, bk.getSex());
psmt.setString(4, bk.getPublisher());
psmt.setString(5, bk.getBookdes());
psmt.setInt(6, bk.getBooktypeid());
return psmt.executeUpdate();
} public int delBook(Connection conn,Book bk) throws Exception
{
String sql="delete from t_book where id ='"+bk.getId() +"'";
PreparedStatement psmt=conn.prepareStatement(sql);
return psmt.executeUpdate();
} public int bookModify(Connection con,Book bk)throws Exception{
String sql="update t_booktype set booktypename=?,booktypedes=? where id=?";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, bk.getBookname());
pstmt.setString(2, bk.getBookdes());
pstmt.setInt(3, bk.getId());
return pstmt.executeUpdate();
} public ResultSet bookList(Connection con,Book book)throws Exception{
StringBuffer sb=new StringBuffer("SELECT t_book.id,t_book.bookname,t_book.author,t_book.sex,t_book.publisher,t_book.bookdes,t_booktype.booktypename FROM t_book,t_booktype WHERE t_book.booktypeid=t_booktype.id");
if(StrUtil.isNotEmpty(book.getBookname())){
sb.append(" and bookname like '%"+book.getBookname()+"%'");
}
if(StrUtil.isNotEmpty(book.getAuthor())){
sb.append(" and author like '%"+book.getAuthor()+"%'");
}
if(StrUtil.isNotEmpty(book.getSex())){
sb.append(" and sex = '"+book.getSex()+"'");
}
if(book.getBooktypeid()!=-1){
sb.append(" and booktypeid = "+book.getBooktypeid());
} PreparedStatement pstmt=con.prepareStatement(sb.toString());
return pstmt.executeQuery();
}
public ResultSet bookListAll(Connection con,Book book)throws Exception{
StringBuffer sb=new StringBuffer("SELECT t_book.id,t_book.bookname,t_book.author,t_book.sex,t_book.publisher,t_book.bookdes,t_booktype.booktypename FROM t_book,t_booktype WHERE t_book.booktypeid=t_booktype.id");
PreparedStatement pstmt=con.prepareStatement(sb.toString());
return pstmt.executeQuery();
}
public boolean getBookByBookTypeId(Connection con,String bookTypeId)throws Exception{
String sql="select * from t_book where booktypeid=?";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, bookTypeId);
ResultSet rs=pstmt.executeQuery();
return rs.next();
}
}

2、依旧是JDBC方法。Dao类採用简单模版方法   练手实例 源码管理系统

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import util.DBHelper; interface RowMapImpl {
abstract Object rowMap(ResultSet rs) throws Exception; abstract List<Object> rowMapList(ResultSet rs) throws Exception;
} public class BaseDao implements RowMapImpl {
public Object query(String sql, Object[] args, RowMapImpl rowMapImpl)
throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
conn = DBHelper.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
ps.setObject(i + 1, args[i]);
rs = ps.executeQuery();
Object obj = null;
if (rs.next()) {
obj = rowMapImpl.rowMap(rs);
}
return obj;
} public List<Object> queryList(String sql, Object[] args,
RowMapImpl rowMapImpl) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Object> list = null;
conn = DBHelper.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
ps.setObject(i + 1, args[i]);
rs = ps.executeQuery();
list = new ArrayList<Object>();
list = rowMapImpl.rowMapList(rs);
return list;
} public int operate(String sql, Object[] args) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
conn = DBHelper.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
ps.setObject(i + 1, args[i]);
return ps.executeUpdate();
} @Override
public Object rowMap(ResultSet rs) throws Exception {
// TODO Auto-generated method stub
return null;
} @Override
public List<Object> rowMapList(ResultSet rs) throws Exception {
// TODO Auto-generated method stub
return null;
} }
package dao;

import java.sql.ResultSet;
import java.util.List; import model.Content; public class ContentDao {
private BaseDao template = new BaseDao();
public int addTree(Content cont) throws Exception {
String sql = "insert into t_content values(? ,?,?)";
Object[] args = new Object[] { cont.getNodeId(), cont.getContent(),
cont.getUpdateTime() };
return template.operate(sql, args);
} public int delTree(Content cont) throws Exception {
String sql = "delete from t_content where NodeId=?";
Object[] args = new Object[] { cont.getNodeId() };
return template.operate(sql, args);
} public int updateTree(Content cont) throws Exception {
String sql = "update t_content set NodeId=? , Content=? UpdateTime=? ";
Object[] args = new Object[] { cont.getNodeId(), cont.getContent(),
cont.getUpdateTime() };
return template.operate(sql, args);
} public Content findTree(String NodeId) throws Exception {
String sql = "select * from t_content where NodeId=? ";
Object[] args = new Object[] { NodeId };
Object cont = template.query(sql, args, new RowMapImpl() {
public Object rowMap(ResultSet rs) throws Exception {
Content cont = new Content();
cont.setNodeId(rs.getInt("NodeId"));
cont.setContent(rs.getString("Content"));
cont.setUpdateTime(rs.getString("UpdateTime"));
return cont;
} @Override
public List<Object> rowMapList(ResultSet rs) throws Exception {
// TODO 自己主动生成的方法存根
return null;
}
});
return (Content) cont;
}
}

3、myBatis訪问  就是xml文件配置比較烦,用起来舒服些。  实例測试。

package util;
import java.io.IOException;
import java.io.Reader; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class DBHelper { <p>
 private static SqlSessionFactory sessionFactory;
 private static Reader reader;
 private DBHelper(){}</p><p> public static SqlSessionFactory getSessionFactory() throws Exception{
  
  String resource = "util/config.xml";
  //载入mybatis的配置文件(它也载入关联的映射文件)
  try {
   reader = Resources.getResourceAsReader(resource);
  } catch (IOException e) {   
   e.printStackTrace();
  }
  //构建sqlSession的工厂
  sessionFactory = new SqlSessionFactoryBuilder().build(reader);
  
  return sessionFactory;</p> }
<?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="dao.UserDao">
<select id="getUser" parameterType="int"
resultType="User">
select * from t_user where id=#{id}
</select>
<select id="getAllUser" resultType="User">
select * from t_user
</select>
<delete id="deleteUser" parameterType="int" >
delete from t_user where id=#{id}
</delete>
<update id="updateUser" parameterType="User">
update t_user set username=#{username}, password=#{password} where id=#{id}
</update>
<insert id="insertUser" parameterType="User">
insert into t_user(username,password) values(#{username},#{password})
</insert> </mapper>
package dao;

import java.util.List;

import model.User;

public interface UserDao {

	public User getUser(int i);

	public List<User> getAllUser();

	public int insertUser(User u);

	public int updateUser(User u);

	public int deleteUser(int i);

}
public static void main(String[] args) throws Exception {
SqlSession session=DBHelper.getSessionFactory().openSession(true);
UserDao userDao=session.getMapper(UserDao.class);
User user=userDao.getUser(1);
System.out.println(user.getUsername());
}

Java数据库訪问小结的更多相关文章

  1. 数据库訪问技术之JDBC

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/zhuojiajin/article/details/32150883     在了解JDBC之前呢, ...

  2. 学习实践:使用模式,原则实现一个C++数据库訪问类

    一.概述 在我參与的多个项目中.大家使用libMySQL操作MySQL数据库,并且是源代码级复用,在多个项目中同样或相似的源代码.这种复用方式给开发带来了不便. libMySQL的使用比較麻烦.非常e ...

  3. java后台訪问url连接——HttpClients

    java后台訪问url,并传递数据--通过httpclient方式 须要的包,包可能多几个额外的,假设无用或者冲突删除就可以.httpclient是使用的是4.4.1的版本号:http://downl ...

  4. 假设在本地搭一个server和mysql数据库环境,假设使用java来訪问数据库

    我们能够使用speedamp来搭一个server环境,能够在http://download.csdn.net/detail/baidu_nod/7630265下载 解压后无需安装直接能够使用.点击Sp ...

  5. java中訪问修饰符

    较之c++ 中 public,proctected, private 三种訪问控制, java多了默认訪问控制. java中四种訪问控制权限 简单描写叙述为一下四句: 1)private 仅本类可见 ...

  6. c#数据库訪问返回值类型为SqlDataReader时使用using时注意的问题

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u010512579/article/details/24011761 在封装通用 SQLSERVER ...

  7. Java 訪问权限控制:你真的了解 protected keyword吗?

    摘要: 在一个类的内部,其成员(包含成员变量和成员方法)是否能被其它类所訪问,取决于该成员的修饰词:而一个类是否能被其它类所訪问,取决于该类的修饰词.Java的类成员訪问权限修饰词有四类:privat ...

  8. JAVA设计模式之 訪问者模式【Visitor Pattern】

    一.概述 訪问者模式是一种较为复杂的行为型设计模式,它包括訪问者和被訪问元素两个主要组成部分.这些被訪问的元素通常具有不同的类型,且不同的訪问者能够对它们进行不同的訪问操作.在使用訪问者模式时,被訪问 ...

  9. 使用ADO.NET对SQL Server数据库进行訪问

    在上一篇博客中我们给大家简介了一下VB.NET语言的一些情况,至于理论知识的学习我们能够利用VB的知识体系为基础.再将面向对象程序设计语言的知识进行融合便可进行编程实战. 假设我们须要訪问一个企业关系 ...

随机推荐

  1. C++函数传递数组的两种方式

    数组与指针. 传首地址过去,然后通过地址输出数组元素. 1.一维数组 #include<iostream> using namespace std; #include <cstrin ...

  2. redis基本数据类型和对应的底层数据结构

    Redis的数据类型包含string,list,hash,set,sorted set. Redis中定义了一个对象的结构体: /* * Redis 对象 */ typedef struct redi ...

  3. sql查询语句中on和where的区别

    sql中的连接查询分为3种, cross join,inner join,和outer join ,  在 cross join和inner join中,筛选条件放在on后面还是where后面是没区别 ...

  4. POJ 2447

    挺水的一题.其实只要理解了RSA算法,就知道要使用大整数分解的方法来直接模拟了. 不过,要注意两个INT64的数相乘来超范围 #include <iostream> #include &l ...

  5. [Python Test] Use pytest fixtures to reduce duplicated code across unit tests

    In this lesson, you will learn how to implement pytest fixtures. Many unit tests have the same resou ...

  6. dexposed框架Android在线热修复

    移动client应用相对于Webapp的最大一个问题每次出现bug,不能像web一样在server就完毕修复,不须要发版本号.紧急或者有安全漏洞的问题, 假设是Webapp你可能最多花个1,2个小时紧 ...

  7. 苹果要求全部新app以及版本号更新必须支持iOS 8 SDK和64-bit

    2014年10月20日.苹果官方公布了一则新闻,新闻内容例如以下: Starting February 1, 2015, new iOS apps uploaded to the App Store ...

  8. 安装Oracle RAC 11g

    1.Oracle Enterprise Linux 和 iSCSI 上构建 Oracle RAC 11g 集群 2.Oracle RAC 的所有共享磁盘存储将基于 iSCSI,iSCSI 使用在第三个 ...

  9. Laravel-HTTP-验证

    Laravel-HTTP-验证 标签(空格分隔): php 第一种方式 **1 直接在controller里完成表单验证** **2 打印验证返回的错误信息 dd($errors)** 第二种方式 * ...

  10. AbstractQueuedSynchronizer中CAS的疑惑

    这段代码是AQS框架中将当前节点入队的操作. Node pred = tail; if (pred != null) { node.prev = pred; if (compareAndSetTail ...