Java Database Access Summary

Source: Internet
Author: User
Tags access database stringbuffer

1. JDBC Access method

DBHelper class Access database, DAO class write data access, view class to apply, a beginner instance book management system.

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 auto-generated catch block E.printstacktrace ();} } private DBHelper () {} public static Connection getconnection () throws Exception {if (c    Onn==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 val UEs (null,?,?,?,?,?,?) "; PreparedStatement psmt=conn.preparestatement (SQL);p smt.setstring (1, Bk.getbookname ());p smt.setstring (2, Bk.getauthor ());p smt.setstring (3, Bk.getsex ());p smt.setstring (4, Bk.getpublisher ());p smt.setstring (5, Bk.getbookdes ());p Smt.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 () + "'";P Reparedstatement 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);p stmt.setstring (1, Bk.getbookname ());p Stmt.setstrING (2, bk.getbookdes ());p Stmt.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);p stmt.setstring (1, Booktypeid); ResultSet rs=pstmt.executequery (); return Rs.next ();}}

2, still is the JDBC method, the DAO class uses the simple template method practiced hand the instance source code management system

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 Ex ception {Connection conn = null; PreparedStatement PS = null; ResultSet rs = Null;conn = Dbhelper.getconnection ();p s = 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 = n Ull PreparedStatement PS = null; ResultSet rs = null; list<object> list = Null;conn = Dbhelper.getconnection ();p s = conn.prepArestatement (SQL); for (int i = 0; i < args.length; i++) Ps.setobject (i + 1, args[i]); rs = Ps.executequery (); list = new A Rraylist<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 ();p s = conn.preparestatement (sql); for (int i = 0; i < Args.le Ngth; i++) Ps.setobject (i + 1, args[i]); return ps.executeupdate ();} @Overridepublic Object Rowmap (ResultSet rs) throws Exception {//TODO auto-generated method Stubreturn null;} @Overridepublic list<object> rowmaplist (ResultSet rs) throws Exception {//TODO auto-generated method Stubreturn nu ll;}}

Package Dao;import Java.sql.resultset;import Java.util.list;import model. Content;public class Contentdao {private Basedao template = new Basedao ();p ublic int Addtree (Content cont) throws Exceptio n {String sql = "INSERT into t_content values (?,?,?)"; O bject[] 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=?"; O bject[] 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=?"; O bject[] 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 (R S.getint ("NodeId")), Cont.setcontent (rs.getstring ("Content")), Cont.setupdatetime (rs.getstring ("UpdateTime")); Return cont;} @Overridepublic list<object> rowmaplist (ResultSet rs) throws Exception {//TODO auto-generated method stub return null;}}); Return (Content) cont;}}

3, MyBatis Access is the XML file configuration is more annoying, comfortable to use. Instance test.

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 {private static sqlsessionfactory sessionfactory;private static Reader reader;private dbhelper () {}static {String resource = "util/config.xml";//load MyBatis configuration file (It also loads the associated mapping file) try {reader = Resources.getresourceasreader ( Resource);} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}} public static Sqlsessionfactory Getsessionfactory () throws exception{//build sqlsession factory sessionfactory = new Sqlsessionfactorybuilder (). build (reader); return sessionfactory;}}

<?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);p ublic list<user> getalluser ();p ublic int Insertuser ( User u);p ublic int UpdateUser (user u);p ublic 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 Database Access Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.