package com.erik.mysql_;
import com.erik.util.JdbcUtil;
import java.sql.*;
public class MysqlIndex {
public static void main(String[] args) throws Exception {
// 获取连接对象
Connection connection = JdbcUtil.getConnection();
// 开启事务
connection.setAutoCommit(false);
try {
// 定义sql语句
String sql = "SELECT * FROM USER where user_id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
// 设置参数
statement.setInt(1, 1);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getInt("user_id"));
System.out.println(resultSet.getString("img"));
}
JdbcUtil.close(resultSet, statement, connection);
connection.commit();
} catch (Exception e) {
connection.rollback();
e.printStackTrace();
}
}
}
使用预处理技术
package com.erik.mysql_;
import com.erik.util.JdbcUtil;
import java.sql.*;
public class MysqlIndex {
public static void main(String[] args) throws Exception {
// 获取连接对象
Connection connection = JdbcUtil.getConnection();
// 定义sql语句
String sql = "SELECT * FROM USER where user_id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
// 设置参数
statement.setInt(1, 1);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getInt("user_id"));
System.out.println(resultSet.getString("img"));
}
JdbcUtil.close(resultSet, statement, connection);
}
}
package com.erik.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JdbcUtil {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
Properties properties = new Properties();
Class<JdbcUtil> aClass = JdbcUtil.class;
String path = aClass.getClassLoader().getResource("pro.properties").getPath();
try {
properties.load(new FileReader(path));
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取链接对象
*
* @return
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Statement statement, Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (SQLException throwable) {
throwable.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
if (statement != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
close(statement, connection);
}
}
c3p0 的使用
简述:c3p0 是javax.sql.DataSource的实现类,数据库连接池的一种,还有druip,非常优秀,是阿里出品。
package com.erik.c3p0Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class Index {
public static void main(String[] args) throws SQLException {
DataSource source = new ComboPooledDataSource();
for (int i = 0; i <= 11; i++) {
Connection connection = source.getConnection();
System.out.println(i + ": " + connection);
}
}
}
- 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/book</property>
<property name="user">root</property>
<property name="password">root</property>
<!--初始化连接的数量-->
<property name="initialPoolSize">10</property>
<!--等待时间-->
<property name="maxIdleTime">3</property>
<!--最大连接数-->
<property name="maxPoolSize">10</property>
<!--最小连接数-->
<property name="minPoolSize">10</property>
</default-config>
<named-config name="mySource">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/book</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">3</property>
<property name="maxPoolSize">10</property>
<property name="minPoolSize">10</property>
</named-config>
</c3p0-config>
druip
的使用
package com.example.demoLogin.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcUtil {
private static DataSource ds;
private static String driver;
static {
// 读取配置文件
InputStream resourceAsStream = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
Properties properties = new Properties();
try {
properties.load(resourceAsStream);
driver = properties.getProperty("driverClassName");
// 导入驱动
Class.forName(driver);
// 初始化数据库连接池
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据源
*
* @return
*/
public static DataSource getDatasource() {
return ds;
}
/**
* 获取连接池对象
*
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
- 配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/book
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
maxIdle=8
minIdle=3
- 使用
package com.example.demoLogin.dao;
import com.example.demoLogin.doman.User;
import com.example.demoLogin.util.JdbcUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.SQLException;
public class UserDao {
/**
* 获取template
*/
private JdbcTemplate template = new JdbcTemplate(JdbcUtil.getDatasource());
/**
* 获取用户
* @param loginUser
* @return
* @throws SQLException
*/
public User getUserById(User loginUser) throws SQLException {
String name = loginUser.getName();
String password = loginUser.getPassword();
String sql = "SELECT * FROM USER WHERE name = ? and password = ?";
User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), name, password);
return user;
}
}
jdbTemp
package com.erik.jdbcTmp;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
public class JdbcTempDemo1 {
public static void main(String[] args) {
// 获取DataSource
DataSource source = new ComboPooledDataSource(); // 也可以使用druip的连接池
JdbcTemplate jdbcTemplate = new JdbcTemplate(source);
String sql = "SELECT * FROM ADDRESS";
// 封装为javaBean对象
List<Address> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Address>(Address.class));
// jdbcTemplate.queryForList(sql); // 多条记录
// jdbcTemplate.queryForMap(sql); // 单条记录
// jdbcTemplate.queryForObject(sql, Long.class); // 聚合函数
System.out.println(query);
}
}
package com.erik.jdbcTmp;
public class Address {
private Integer address_id;
private Integer user_id;
private String name;
private String phone_number;
private Integer create_time;
public Address() {
}
public Address(Integer address_id, Integer user_id, String name, String phone_number, Integer create_time) {
this.address_id = address_id;
this.user_id = user_id;
this.name = name;
this.phone_number = phone_number;
this.create_time = create_time;
}
public Integer getAddress_id() {
return address_id;
}
public void setAddress_id(Integer address_id) {
this.address_id = address_id;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public Integer getCreate_time() {
return create_time;
}
public void setCreate_time(Integer create_time) {
this.create_time = create_time;
}
@Override
public String toString() {
return "Address{" +
"address_id=" + address_id +
", user_id=" + user_id +
", name='" + name + '\'' +
", phone_number='" + phone_number + '\'' +
", create_time=" + create_time +
'}';
}
}