码迷,mamicode.com
首页 > 数据库 > 详细

数据库增删改查及优化

时间:2016-12-03 23:33:07      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:类加载   执行   bst   rpc   java   not   arraylist   state   val   

创建一个工程,导入所需jar包,本例使用MySQL数据库,Navicat可视化工具,使用开源的c3p0连接池,采用单元测试,结构如下:

技术分享

 

例中用到的表:

技术分享

应用程序直接获取连接有很多缺点:

技术分享

而使用数据库连接池大大提升程序性能:数据库连接池负责分配,管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个

技术分享

 下面是代码部分:

  StudentPO 类:

package po;
import java.util.Date;
public class StudentPO
{
private String sno;
private String name;
private char sex;
private Date birthday;
public StudentPO(String sno, String name, char sex, Date birthday) {
this();
this.sno = sno;
this.name = name;
this.sex = sex;
this.birthday = birthday;
}
public StudentPO()
{
super();
// TODO Auto-generated constructor stub
}

public String getSno()
{
return sno;
}

public void setSno(String sno)
{
this.sno = sno;
}
public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}
public char getSex()
{
return sex;
}
public void setSex(char sex)
{
this.sex = sex;
}
public Date getBirthday()
{
return birthday;
}
public void setBirthday(Date birthday)
{
this.birthday = birthday;
}
}

StudentDAOI 类:

package dao;

import java.util.List;

import po.StudentPO;

public interface StudentDAOI
{
public boolean addStudent(StudentPO student);
public boolean delStudent(String sno);
public boolean updStudent(StudentPO student);
public StudentPO getStudentBySno(String sno);
public List<StudentPO> getStudents();
}

 DBUtil 类:

package dao.impl;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public abstract class DBUtil {
// c3p0连接池(优化性能)
private static ComboPooledDataSource dataSource;

static {
String url = "jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8";
String userName = "root";
String password = "sxh";
String driver = "com.mysql.jdbc.Driver";
dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(userName);
dataSource.setPassword(password);
dataSource.setMaxPoolSize(30);
dataSource.setMinPoolSize(10);
dataSource.setMaxStatements(10000);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}

public static Connection getConn() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

// 单例模式
/*
* private static Connection conn = null; static {//类加载的时候就执行 String url =
* "jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8"
* ; String userName = "root"; String password = "sxh";
*
* //SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //
* 不转格式就会出错:Incorrect date value: ‘Sat Nov 26 21:27:48 GMT+08:00 2016‘ try {
* Class.forName("com.mysql.jdbc.Driver"); conn =
* DriverManager.getConnection(url,userName,password); } catch (SQLException
* e) { // TODO Auto-generated catch block e.printStackTrace(); } catch
* (ClassNotFoundException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/

public static boolean cud(String sql, List<Object> params) {
boolean flag = false;
PreparedStatement pstat = null; // 预处理语句
Connection conn = null;
try
{
conn = dataSource.getConnection();
pstat = conn.prepareStatement(sql);

if(params!=null)
{
for(int idx=0;idx<params.size();idx++)
{
pstat.setObject(idx+1, params.get(idx));
}
}

int result = pstat.executeUpdate();
flag = (result>0)?true:false;
}catch (Exception e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
System.out.println(flag);
return flag;
}

public static void close(ResultSet rs,PreparedStatement pstat,Connection conn)
{
try
{
if(rs!=null) rs.close();
if(pstat!=null) pstat.close();
if(conn!=null) conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

 StudentDAOImpl类:

package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import po.StudentPO;
import dao.StudentDAOI;

public class StudentDAOImpl extends DBUtil implements StudentDAOI {
public boolean addStudent(StudentPO student) {
String sql = "insert into t_student values(?,?,?,?)";
List<Object> params = new ArrayList<Object>();
params.add(student.getSno());
params.add(student.getName());
params.add(student.getSex() + "");
params.add(student.getBirthday());
System.out.println(student.getClass());
// 静态方法的使用 ,可用类名或对象名来调用
System.out.println(DBUtil.cud(sql, params));
return DBUtil.cud(sql, params);
}

public boolean delStudent(String sno) {
String sql = "delete from t_student where sno = ?";
List<Object> params = new ArrayList<Object>();
params.add(sno);
return DBUtil.cud(sql, params);
}

public boolean updStudent(StudentPO student) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String sql = "update t_student set name=?,sex=?,birthday=? where sno=?";
List<Object> params = new ArrayList<Object>();
// 四个参数的添加顺序跟SQL语句的参数顺序一致
params.add(student.getName());
params.add(student.getSex() + "");
params.add(student.getBirthday());
params.add(student.getSno());
System.out.println(DBUtil.cud(sql, params));
return DBUtil.cud(sql, params);
}

public StudentPO getStudentBySno(String sno) {
String sql = "select * from t_student where sno = ?";
List<Object> params = new ArrayList<Object>();
params.add(sno);
List<StudentPO> students = gets(sql, params);
return (students.size() > 0) ? students.get(0) : null;
}

public List<StudentPO> getStudents() {
String sql = "select * from t_student";
return gets(sql, null);
}

private List<StudentPO> gets(String sql, List<Object> params) {
List<StudentPO> students = new ArrayList<StudentPO>();

Connection conn = DBUtil.getConn();
PreparedStatement pstat = null;
ResultSet rs = null;
try {
pstat = conn.prepareStatement(sql);

if (params != null) {
for (int idx = 0; idx < params.size(); idx++) {
pstat.setObject(idx + 1, params.get(idx));
}
}

rs = pstat.executeQuery();

StudentPO student = null;
// 用反射可以实现通用
while (rs.next()) {
student = new StudentPO();
student.setSno(rs.getString("sno"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex").charAt(0));
student.setBirthday(rs.getDate("birthday"));
students.add(student);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, pstat, conn);
}
return students;
}
}

 AppMain类:

package app;

import java.util.Date;
import org.junit.Test;

import dao.StudentDAOI;
import dao.impl.StudentDAOImpl;

import po.StudentPO;

public class AppMain
{
private StudentDAOI studentDAO;

public AppMain()
{
studentDAO = new StudentDAOImpl();
}
@Test
public void testAddStudent()
{
StudentPO student = new StudentPO("2","刘嘉玲",‘m‘,new Date());
studentDAO.addStudent(student);
}

@Test
public void testDelStudent()
{
studentDAO.delStudent("1");
}

@Test
public void testUpdStudent()
{
StudentPO student = new StudentPO("2","海星叔",‘m‘,new Date());
studentDAO.updStudent(student);
}

@Test
public void testGetStudentBySno()
{
StudentPO student = studentDAO.getStudentBySno("s001");
System.out.println(student.getName());
}

@Test
public void testGetStudents()
{
List<StudentPO> students = studentDAO.getStudents();
System.out.println(students.size());
}

}

进行单元测试

技术分享

 

技术分享

代码地址:

http://pan.baidu.com/s/1ciRPcq

 

数据库增删改查及优化

标签:类加载   执行   bst   rpc   java   not   arraylist   state   val   

原文地址:http://www.cnblogs.com/MissSu/p/6129617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!