以User為操作對象 原始JDBC 這個註意ResultSet 是一個帶指針的結果集,指針開始指向第一個元素的前一個(首元素),不同於iterator 有hasNext() 和next() ,他只有next() 整合c3p0的DBUtils c3p0整合了連接資料庫的Connection ,提供更快 ...
以User為操作對象
package com.swift.jdbc; public class User { private Long user_id; private String user_code; private String user_name; private String user_password; private String user_state; public User() { super(); // TODO Auto-generated constructor stub } public User(Long user_id, String user_code, String user_name, String user_password, String user_state) { super(); this.user_id = user_id; this.user_code = user_code; this.user_name = user_name; this.user_password = user_password; this.user_state = user_state; } public Long getUser_id() { return user_id; } public void setUser_id(Long user_id) { this.user_id = user_id; } public String getUser_code() { return user_code; } public void setUser_code(String user_code) { this.user_code = user_code; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getUser_password() { return user_password; } public void setUser_password(String user_password) { this.user_password = user_password; } public String getUser_state() { return user_state; } public void setUser_state(String user_state) { this.user_state = user_state; } @Override public String toString() { return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password=" + user_password + ", user_state=" + user_state + "]"; } }
原始JDBC
這個註意ResultSet 是一個帶指針的結果集,指針開始指向第一個元素的前一個(首元素),不同於iterator 有hasNext() 和next() ,他只有next()
package com.swift.jdbc; import java.beans.PropertyVetoException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DemoJDBC { public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException { findAll(); User user=findById(9l); System.out.println(user); user.setUser_name("HanMeimei"); update(user); } private static void update(User user) throws PropertyVetoException, SQLException { ComboPooledDataSource dataSource=new ComboPooledDataSource(); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/crm"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setPassword("root"); dataSource.setUser("root"); dataSource.setMinPoolSize(5); dataSource.setMaxIdleTime(2000); Connection con= dataSource.getConnection(); String sql="update sys_user set user_name='"+user.getUser_name()+"' where user_id="+user.getUser_id(); PreparedStatement statement = con.prepareStatement(sql); statement.executeUpdate(); System.out.println("ok"); } private static User findById(long id) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","root"); Statement statement = con.createStatement(); ResultSet rs = statement.executeQuery("select * from sys_user where user_id="+id); User user=null; while(rs.next()) { user=new User(rs.getLong("user_id"),rs.getString("user_code"), rs.getString("user_name"),rs.getString("user_password"), rs.getString("user_state")); } return user; } private static void findAll() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm?user=root&password=root"); PreparedStatement statement = connection.prepareStatement("select * from sys_user"); ResultSet rs = statement.executeQuery(); List<User> list=new ArrayList<>(); while(rs.next()) { Long id = rs.getLong("user_id"); String code=rs.getString("user_code"); String name=rs.getString("user_name"); String password=rs.getString("user_password"); String state=rs.getString("user_state"); User user=new User(); user.setUser_code(code); user.setUser_id(id); user.setUser_password(password); user.setUser_name(name); user.setUser_state(state); list.add(user); } for(User u:list) { System.out.println(u); } rs.close(); connection.close(); } }
整合c3p0的DBUtils
c3p0整合了連接資料庫的Connection ,提供更快速的連接
package com.swift.c3p0; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Utils { private static ComboPooledDataSource dataSource = new ComboPooledDataSource(); private static ThreadLocal<Connection> thread=new ThreadLocal<>(); // static { // try { // dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/crm"); // dataSource.setDriverClass("com.mysql.jdbc.Driver"); // dataSource.setUser("root"); // dataSource.setPassword("root"); // dataSource.setMinPoolSize(5); // } catch (PropertyVetoException e) { // e.printStackTrace(); // } // } public static DataSource getDataSource() { return dataSource; } public static Connection getConnection() { Connection con = thread.get(); if(con==null) { try { con = dataSource.getConnection(); thread.set(con); con=thread.get(); } catch (SQLException e) { e.printStackTrace(); } } return con; } public static void main(String[] args) { Connection con = C3P0Utils.getConnection(); System.out.println(con); } }
並可以直接載入xml配置文件,強於(DBCP連接池,他只支持properties文件)
<c3p0-config> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/crm</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password">root</property> </default-config> </c3p0-config>
DBUtils的殺手鐧QueryRunner
可以使用?了,放置惡意註意,也提供自動增加' '符號,這個要註意
package com.swift.dbutils; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.swift.c3p0.C3P0Utils; import com.swift.jdbc.User; public class DemoQueryRunner { private static QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource()); static List<User> users=new ArrayList<User>(); public static void main(String[] args) throws SQLException { //查找所有 users=findAll(); for(User user:users) { System.out.println(user); } //通過Id查找 User user=findById(9l); System.out.println(user); //更新 user.setUser_name("韓梅梅"); System.out.println("==================================="); System.out.println(user); update(user); } private static void update(User user) throws SQLException { int update = qr.update( "update sys_user set user_name=? where user_id=?",user.getUser_name(),user.getUser_id()); System.out.println(user.getUser_name()+update); } private static List<User> findAll() throws SQLException { List<User> users = qr.query("select * from sys_user ", new BeanListHandler<User>(User.class)); return users; } private static User findById(long l) throws SQLException { User user = qr.query( "select * from sys_user where user_id=?",new BeanHandler<User>(User.class),l); return user; } }
Hibernate 有個核心配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <!-- 約束在hibernate-core-5.0.7.Final.jar的org.hibernate包下的hibernate-configuration-3.0.dtd文件中找 --> <hibernate-configuration> <session-factory> <!-- 配置方法:資料\hibernate-release-5.0.7.Final\project\etc\hibernate.properties --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/crm</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.max_size">10</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.timeout">5000</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.connection.isolation">2</property> <!-- 獲得當前session放在當前線程中 --> <!-- <property name="hibernate.current_session_context_class">thread</property> --> <mapping resource="com/swift/hibernate/User.hbm.xml"/> </session-factory> </hibernate-configuration>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
這個是使用Hibernate自帶的c3p0功能,不需要自己寫c3p0.xml文件,但除了需要c3p0的jar包,還需要Hibernate自帶的jar包,可以在hibernate包的lib->optional->c3p0中找到,
此文件夾中這兩個jar:c3p0-0.9.1.jar和hibernate-c3p0-4.2.1.Final.jar都要用,否則異常
Could not instantiate connection provider [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider]
還有個實體類的映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- 約束在hibernate-core-5.0.7.Final.jar的org.hibernate包下的hibernate-mapping-3.0.dtd文件中找 --> <hibernate-mapping> <class name="com.swift.hibernate.User" table="sys_user"> <id name="user_id" column="user_id"> <generator class="native"></generator> </id> <property name="user_code" column="user_code"></property> <property name="user_name" column="user_name"></property> <property name="user_password" column="user_password"></property> <property name="user_state" column="user_state"></property> </class> </hibernate-mapping>
連接資料庫是通過session
package com.swift.hibernate; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class DemoHibernate { static List<User> users=new ArrayList<User>(); public static void main(String[] args) { users=findAll(); for(User user:users) { System.out.println(user); } } private static List<User> findAll() { //new Configuration()是創建Configuration類對象,調用裡面的configure方法,讀取配置信息,方法返回的又是Configuration類型 Configuration config=new Configuration().configure(); SessionFactory sf = config.buildSessionFactory(); Session session = sf.openSession(); Query query = session.createQuery("from User"); users= query.list(); session.close(); return users; } }
使用Spring的jdbcTemplate
關於倒包
Spring 總共有20個包看需要導入,其他還有spring的官方擴展包 (整合的較常用的一些,可根據功能導入)
這裡只要實現資料庫,所以,倒spring的4個核心包beans context core expression 2個日誌log4j commons-loging(可不倒)
c3p0要倒 連接資料庫mysql-connector-java 還有Spring的spring-jdbc 事務spring-tx 用註解要spring-aop
配置文件菜單法生成
applicationContext.xml(非官方約定俗成的,其實叫什麼都可以)
約束如果不想拷貝,可以用菜單導入 window --> preferences -->搜索(xml catalog) -->add-->file system(註意:把location最後的約束文件名複製到key的最後)
導入後
在xml配置文件中,輸入Spring的根標簽<beans></beans> 然後切換到design視圖右擊選擇 -->namespace-->勾選xsi(這時約束的約束,必須有,控制後面所有)
-->add-->specify new namespace -->location hint (把剛纔添加的約束導入)-->把去約束文件名的網址複製到 namespace name -->prefix隨便起個名(一般叫約束名
)
最後註意:beans不要有prefix 要設置為空,否則沒有標簽提示
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <context:component-scan base-package="com.swift"></context:component-scan> <context:property-placeholder location="classpath:db.properties"/> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> </bean> </beans>
<context:property-placeholder location="classpath:db.properties"/>
掃描src目錄下的properties文件使用${key}載入value 據說是spring的el語言spel
感覺這裡直接寫也可以,單獨拿到properties文件里可能不會感覺亂哄哄一堆
測試結果
package com.swift.jdbctemplate; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; public class DemoJdbcTemplate { private static ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); private static DataSource dataSource = (DataSource) context.getBean("dataSource"); private static JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource); public static void main(String[] args) throws SQLException { User user=new User(null,null,"甲魚不是龜","456","0"); add(user); List<User> users=new ArrayList<>(); users=findAll(); System.out.println(users); user=findById(23l); System.out.println(user); } private static User findById(long l) { return jdbcTemplate.queryForObject( "select * from sys_user where user_id=?", new BeanPropertyRowMapper<User>(User.class),l); } private static List<User> findAll() { return jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class)); } private static void add(User user) { jdbcTemplate.update("insert into sys_user values(?,?,?,?,?)", null,null,user.getUser_name(),user.getUser_password(),user.getUser_state()); System.out.println("插入記錄成功"); } }