数据库访问-笔记
日前,接到一个把数据库数据同步到Redis里的小任务,在编写代码时需要用到几个数据库查询的操作,但jar包里并没有集成这几个功能。
由于,这个同步任务只需要进行一次,并没有必要到jar包里添加这几个操作的方法,所以就在代码里自己编写了一个数据库访问和查询的操作。
1.添加pox依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
|
2.建立数据库链接
2.1. 数据库配置:database-xmparty.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://****:4444?autoReconnect=true&useUnicode=true&zeroDateTimeBehavior=convertToNull username=*** password=*** #<!-- 初始化连接 --> initialSize=10 #最大连接数量 maxActive=50 #<!-- 最大空闲连接 --> maxIdle=20 #<!-- 最小空闲连接 --> minIdle=5 #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 --> maxWait=60000 #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。 connectionProperties=useUnicode=true;characterEncoding=gbk #指定由连接池所创建的连接的自动提交(auto-commit)状态。 defaultAutoCommit=true #driver default 指定由连接池所创建的连接的只读(read-only)状态。 #如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix) defaultReadOnly= #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。 #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE defaultTransactionIsolation=2 |
2.2. 初始化
@Named
public final class Temple {
private static BasicDataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
private Temple() { }
static {
try {
Class.forName("com.mysql.jdbc.Driver");
Properties pro = new Properties();
InputStream in = Temple.class.getClassLoader().getResourceAsStream("database-xmparty.properties");
pro.load(in);
dataSource = BasicDataSourceFactory.createDataSource(pro);//注意这段代码!!!
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void free(Connection con, Statement st, ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|
上面的是在代码中初始化databbase,下面用spring配置来初始化databbase:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd">
<context:property-placeholder location="classpath:database-xmparty.properties"/>
<bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
<property name="maxWait" value="${maxWait}"/>
<property name="connectionProperties" value="${connectionProperties}"/>
<property name="defaultAutoCommit" value="${defaultAutoCommit}"/>
<property name="defaultTransactionIsolation" value="${defaultTransactionIsolation}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="basicDataSource"/>
</bean>
<!--<mybatis:scan base-package="com.sankuai.xm.**.dao"/>-->
</beans>
|
Templ.class里就可以进一步修改:
@Named
public final class Temple {
@Inject
private BasicDataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void free(Connection con, Statement st, ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|
3. 数据库访问
通过上面的配置, 我们已经建立数据库的链接,下面我们就可以正常访问了:
/**
* Created by Endstart on 15/7/15.
*/
@Named
public class SyncService {
private static final Logger log = LoggerFactory.getLogger(SyncService.class);
private PartyBasicService partyBasicService = PartyBeans.get(PartyBasicService.class);
@Inject
private Temple temple;
public List<Roster> getRosterByRosterPid(long roster_pid) {
try {
JdbcTemplate jdbc = new JdbcTemplate(temple.getDataSource());
String sql = "select * from roster where roster_pid=? and status=1";
Object[] args = new Object[]{roster_pid};
@SuppressWarnings("unchecked")
List<Roster> rosterList = jdbc.query(sql, args, new BeanPropertyRowMapper(Roster.class));
return rosterList;
} catch (Exception e) {
log.warn("服务器错误", e);
return null;
}
}
public List<Roster> getRosterByRosterPid(String jid) {
PartyBasic partyBasic = partyBasicService.getPartyBasicByMain(jid);
return getRosterByRosterPid(partyBasic.getId());
}
}
|

浙公网安备 33010602011771号