//数据库连接的中间产物,放在try外面,便于关闭,节约资源。
Connection connection = null;
Statement Statement = null;
ResultSet resultSet = null;
try {
//1 注册数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2 获取数据库连接 数据库名:mydatabase
// 用户名:root 密码:123
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "root", "123");
//3 获取语句执行平台
String sql ="SELECT * FROM book";
statement = connection.createStatement();
//4 执行sql语句
resultSet = statement.executeQuery(sql);
//5 结果处理
while (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getInt("id"));
book.setName(resultSet.getString("name"));
book.setPrice(resultSet.getFloat("price"));
book.setPic(resultSet.getString("pic"));
book.setDescription(resultSet.getString("description"));
list.add(book);
}
//释放资源
connection.close();;
preparedStatement.close();
resultSet.close();
其中,sql语句执行增删改时,返回操作成功的行数。
int row = preparedStatement.executeQuery(sql);
当sql语句执行查的时候,返回查找结果的集合。
ResultSet resultSet = preparedStatement.executeQuery(sql);
数据库注入的解释在此就不说了。
//数据库连接的中间产物,放在try外面,便于关闭,节约资源。
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1 注册数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2 获取数据库连接
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "root", "123");
//3 获取语句执行平台
String sql = "SELECT * FROM user WHERE username=? AND PASSWORD=?";
//注意sql代入的语句由于上文不一样
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,"zhangsan");
preparedStatement.setObject(2,123);
//4 执行sql语句
resultSet = preparedStatement.executeQuery();
//5 结果处理
while (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getInt("id"));
book.setName(resultSet.getString("name"));
book.setPrice(resultSet.getFloat("price"));
book.setPic(resultSet.getString("pic"));
book.setDescription(resultSet.getString("description"));
list.add(book);
}
//释放资源
connection.close();;
preparedStatement.close();
resultSet.close();
将数据库驱动,URL,用户名,密码4各参数写到配置文件中,这样只需要修改配置文件,提高代码的复用性。
配置文件名:.properties结尾
位置:建议src下面
内容:一行一组数据,可以不要分号
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:// /mydatabase
username=root
password=123
连接池技术优点:连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。
使用DBCP连接池需要两个jar包,commons-dbcp.jar,commons-pool.jar,包中定义好一个类,实现类数据源的规范接口javax.sql.DataSource.
BasicDataSource dataSource = new BasicDataSource();
dataSource .setDriverClassName("com.mysql.jdbc.Driver");
dataSource .setUrl("jdbc:mysql://localhost:3306/myDatabase");
dataSource .setUsername("root");
dataSource .setPassword("123");
Connection con = dataSource.getConnection();
.......(省略)
步骤:
1、导入jar包,c3p0-0.9.5.2.jar,mchange-chommons-java.jar数据库支持包
2、定义配置文件
名称:.properties
路径:建议src目录下
3、创建核心对象,数据库连接池对象ComboPooledDataSource
4、获取连接 getConnection
c3p0-config.xml
<c3p0-config>
<!-- 使用默认的配置读取连接池对象 -->
<default-config>
<!-- 连接参数 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="user">root</property>
<property name="password">123</property>
<!-- 连接池参数 -->
<!-- 初始化申请的连接数量-->
<property name="initialPoolSize">5</property>
<!-- 最大的连接数量-->
<property name="maxPoolSize">10</property>
<!-- 超时时间 -->
<property name="checkoutTimeout">3000</property>
</default-config>
<named-config name="otherc3p0">
<!-- 连接参数 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day25</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 连接池参数 -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">8</property>
<property name="checkoutTimeout">1000</property>
</named-config>
</c3p0-config>
连接
//默认配置文件
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//使用指定的配置文件
//ComboPooledDataSource comboPooledDataSource2 = new ComboPooledDataSource("otherc3p0");
/**
* 获取连接,发现只能最多获取10个,最后会暂停3秒,报错
*/
for (int i = 1; i <= 11; i++) {
Connection connection = comboPooledDataSource.getConnection();
System.out.println(i+":"+connection);
}
Duid数据库连接池技术有阿里巴巴提供
1、导入jar包,druid.1.0.9.jar
2、定义配置文件
3、获得数据库连接池技术,通过工厂获取DuidDataSOurceFactory
4、获得连接 getConnection
duid连接池工具
//1、 定义一个成员变量 datasource
private static DataSource ds;
//静态代码块初始赋值
static{
try {
//加载配置文件
Properties pro = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//获取dataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///mydatabase
username=root
password=123
initialSize=5
maxActive=10
maxWait=3000
获取连接
//加载配置文件
Properties pro = new Properties();
pro.load(DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"));
// String url = pro.getProperty("url");
// String username = pro.getProperty("username");
// String password = pro.getProperty("password");
//获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//获取连接
Connection connection = ds.getConnection();
System.out.println(connection);
/**
* 添加操作,user表添加记录
*/
Connection connection = null;
PreparedStatement pst = null;
try {
connection = JDBCUtils.getConnection();
String sql = "insert into users values(null,?,?)";
pst = connection.prepareStatement(sql);
pst.setObject(1, "caiji");
pst.setObject(2, 1250);
int values = pst.executeUpdate();
System.out.println(values);
} catch (SQLException e) {
e.printStackTrace();
}finally{
JDBCUtils.close(pst,connection);
}