需要导入的jar包:
1、commons-dbutils-1.6.jar
2、mysql-connector-java-5.1.10.jar
获取链接封装:
package com.xingxue.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.commons.dbutils.DbUtils; public class DBUtil { private final static String URL = "jdbc:mysql://localhost:3306/test"; private final static String USER = "root"; private final static String PASSWORD = "asdfghjkl"; private static Connection conn =null; static{ DbUtils.loadDriver("com.mysql.jdbc.Driver"); try { conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败!"); } } public static Connection getConn() { return conn; } }
数据库的查询语句
public class FeiyongDaoImpl implements FeiyongDao { QueryRunner queryRunner = new QueryRunner(); @SuppressWarnings("rawtypes") public ArrayList selectFeiyong() { Connection conn = DBUtil.getConn(); ArrayList list=null; try { String sql = "select * from db"; list = (ArrayList) queryRunner.query(conn, sql,new BeanListHandler<Feiyong>(Feiyong.class)); return list; } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库操作查询异常"); } return list; } }
package com.xingxue.util;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
public class DBUtil {private final static String URL = "jdbc:mysql://localhost:3306/test";private final static String USER = "root";private final static String PASSWORD = "asdfghjkl";private static Connection conn =null;static{DbUtils.loadDriver("com.mysql.jdbc.Driver");try {conn = DriverManager.getConnection(URL, USER, PASSWORD);} catch (SQLException e) {e.printStackTrace();System.out.println("数据库连接失败!");}}public static Connection getConn() {return conn;}}