方式一:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class MyTest {
@Test
public void jdbcTemplateTest(){
//使用JdbcTemplate完成数据库表建立
//1.创建数据库连接池,使用spring内置的连接池
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///flysun");
dataSource.setUsername("root");
dataSource.setPassword("xxxxx");
//2.通过连接池构造模板对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//3.使用Template 执行sql语句
jdbcTemplate.execute("create table person (id int primary key, name varchar(20))");
jdbcTemplate.query("select * from table where id = ?",id);
}
}
方式二,使用properties配置
package Utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class DruidUtlis {
private static DataSource dataSource=null;
static{
InputStream resourceAsStream = DruidUtlis.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
try {
properties.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection(); }
public static DataSource getDataSource() throws SQLException {
return dataSource; }
}
db.properties 文件
url=jdbc:mysql://localhost:3306/test
username=root
password=root
driverClassName=com.mysql.jdbc.Driver
# \u8FDE\u63A5\u6C60\u7684\u53C2\u6570
initialSize=10
#\u8FDE\u63A5\u6C60\u4E2D\u6700\u5927\u652F\u630110\u4E2A\u8FDE\u63A5
maxActive=10
#z\u6700\u5927\u7B49\u5F85\u65F6\u95F4 2\u79D2
maxWait=5000
使用:
//2.通过连接池构造模板对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtlis.getDataSource());
//3.使用Template 执行sql语句
jdbcTemplate.execute("create table person (id int primary key, name varchar(20))");
jdbcTemplate.query("select * from table where id = ?",id);