数据库连接:学习JDBC的主要步骤有:
1、数据库连接:
数据库连接有多种方法:
1) 这是最原始的链接方法:
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost:3306/mysqltest?useUnicode=true&characterEncoding=gbk";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
public Dao() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("链接失败");
}
}
2)
//这种方法与下面的方法的不同之处就在于:这种方法的链接的四个字符串是在类里面赋值的,
//而下面的方法是从 jdbc.properties 配置文件中获取的
public void testDriver() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "");
Connection connection = (Connection) driver.connect(url, info);
System.out.println(connection);
}
3) 参考:jdbc_expression1.Jdbc
//首先从properties文件里获取了资源放在 properties实例里面,
//再通过Driver driver = (Driver) Class.forName(driverClass).newInstance();
//来获取Driver实例,
//传参给driver后就可以通过driver.connection(url,Info)得到 Connection 实例
public Connection getConnection() throws Exception {
String driverClass = null;
String url = null;
String userName = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", userName);
info.put("password", password);
Connection connection = (Connection) driver.connect(url, info);
return connection;
}
4)参考:Jcbc_connedtion.JdbcTools
//通过class.forName(driverClass)来加载
public Connection getConnection2()throws Exception{
String driverClass = null;
String url = null;
String userName = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
url = properties.getProperty("url");
userName = properties.getProperty("userName");
password = properties.getProperty("password");
Class.forName("driverClass");
Connection connection=(Connection) DriverManager.getConnection(url,userName,password);
return connection;
}
5)参考:jdbc_connection.JdbcTools
ComboPooledDataSource()获取了src 目录下的c3p0-config.xml文件 里面的“helloc3p0”的内容
来创建Datasource实例,再有dataSource 获取 connection 实例
private static DataSource dataSource=null;
static{
dataSource=new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnectionByPool() throws SQLException{
return dataSource.getConnection();
}
6)参考:controller.Batch_processed
/**
* 使用数据库连接池:
* @throws SQLException
*
*
*
*/
@Test
public void testDBCP() throws SQLException{
BasicDataSource dataSource=null;
dataSource=new BasicDataSource();
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setUrl("jdbc:mysql:///test");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setInitialSize(10);
dataSource.setMinIdle(5);
dataSource.setMaxWaitMillis(5000);;
Connection connection=dataSource.getConnection();
System.out.println(connection.getClass());
}
7)
参考:.controller.Batch_processed
/**
* 使用工厂模式来创建BasicDataSource,从而创建连接connection
*
* @throws Exception
*/
@Test
public void testDBCPBasicDataSourceFactory() throws Exception{
Properties properties=new Properties();
InputStream inputStream=Batch_processed.class.getClassLoader().
getResourceAsStream("dbcp.properties");
properties.load(inputStream);
DataSource dataSource=BasicDataSourceFactory.createDataSource(properties);
BasicDataSource basicDataSource=(BasicDataSource) dataSource;
System.out.println(dataSource.getConnection());
------------------------------------------------------
2、获取statement;
Statement=connection.createStatement();
preparedStatement=connection.preparedStatement();
1)如果是用statement的话就直接拼写 sql 语句:
2)用 preparedStatement就用setObject(int,Object);
--------------------------------------------------------
3、获取并处理结果集
1); 由结果集转换为bean
//该方法用例 DBUtiles.jar 包中的 import org.apache.commons.dbutils.handlers.BeanHandler/QueryRunner;
Location :Jdbc_practice.bean.BeanUtilTest.java
QueryRunner queryRunner=new QueryRunner();
@Test
public void testBeanHandler(){
Connection connection=null;
try {
connection=JdbcTools.getConnectionByPool();
String sql="select * from book where id=?";
Book book= queryRunner.query(connection, sql, new BeanHandler
(Book.class), 5);
System.out.println(book);
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(null, null, connection);
}
}
2)这是个狭隘的方法:只能用在特定的bean类;
public List getAllBook2()throws Exception{
List list=new ArrayList();
Book book=null;
String sql="select * from book";
Connection connection=JdbcTools.getConnection();
PreparedStatement preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
ResultSet resultSet=preparedStatement.executeQuery();
while(resultSet.next()){
book=new Book();
book.setNumber(resultSet.getInt(1));
book.setBookName(resultSet.getString(2));
book.setAuthor(resultSet.getString(3));
book.setPrice(resultSet.getInt(4));
list.add(book);
}
return list;
}
3) 这是个通用方法:实现方法有两个:(1)通过java反类来实现,(2)通过DBUtils的静态方法
setProperty(T,fieldName,fieldValue)来实现;具体参考.bean.BeanUtileTest
public static T getObject(Class clazz,String sql,Object ... args )throws Exception{
T entity =null;
Connection connection=JdbcTools.getConnection();
PreparedStatement preparedStatement=(PreparedStatement) connection.prepareStatement(sql);
for(int i=0;i preparedStatement.setObject(i+1, args[i]);
}
ResultSet resultSet=preparedStatement.executeQuery();
Mapvalues=new HashMap();
ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
while(resultSet.next()){
for(int i=0;i String columLabel = resultSetMetaData.getColumnLabel(i+1);
Object columValue = resultSet.getObject(columLabel);
values.put(columLabel,columValue);
}
}
if(values.size()>0){
entity=clazz.newInstance();
java.lang.reflect.Field[] field=entity.getClass().getDeclaredFields();
System.out.println("for before");
for(Map.Entryentry : values.entrySet()){
String fieldName=entry.getKey();
Object fieldValue=entry.getValue();
//使用BeanUtils.setProperty(),功能和注释部分一样
BeanUtils.setProperty(entity, fieldName, fieldValue);
// for(int i=0;i // field[i].setAccessible(true);
// try {
// if(field[i].getType().equals(String.class)){
// if(field[i].getName().equals(fieldName)){
// field[i].set(entity, fieldValue);
// }
// }else if(field[i].getType().equals(int.class)){
// if(field[i].getName().equals(fieldName)){
// field[i].set(entity, fieldValue);
// }
// }
// } catch (Exception e) {
// field[i].setAccessible(true);
// }
// }
}
}
return entity;
}
/**
* 这个方法的实现跟上面的差不多;
* 这是将结果集转化为 List 的方法
*/
public static List getObjects(Class clazz,String sql,Object ... args)
throws Exception{
T entity=null;
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
List