jdbc连接数据库
需要导入的第三方库2个
dbutils? ? ? ? druid
加载驱动?
利用druid创建数据库连接池
关闭流操作
package Test;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import java.sql.Statement;
import java.sql.ResultSet;
public class DruidTest {
// 1、加载驱动
//2、获取连接
@Test
public static Connection getConnection() throws Exception {
Properties pros = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");//配置文件地址
pros.load(is);
DataSource source = DruidDataSourceFactory.createDataSource(pros);
Connection connection = source.getConnection();
System.out.println(connection);
return connection;
}
// 关闭流
public static void closeResource1(Connection conn,Statement ps,ResultSet rs){
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(ps);
DbUtils.closeQuietly(rs);
}
}
?????????这是最基本的配置文件
url=jdbc:mysql:///test
username=root
password=abc123
driverClassName=com.mysql.jdbc.Driver
利用封装的dbutils实现增删改查操作
package Test;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;
import java.sql.Connection;
public class QueryRunnerTest {
// 增加一条数据
@Test
public void testInsert() {
Connection conn = null;
try {
QueryRunner runner = new QueryRunner();
conn = DruidTest.getConnection();
String sql = "insert into customers(name,email,birth)values(?,?,?)";
int i = runner.update(conn, sql, "蔡徐坤", "caixukun@126.com", "1997-09-08");
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}finally {
DruidTest.closeResource1(conn, null, null);
}
}
// 查询数据 有多种情况,具体情况具体分析
@Test
public void testQuery() {
Connection connection1 = null;
try {
QueryRunner runner = new QueryRunner();
Connection connection = DruidTest.getConnection();
String sql="select id,name,email,birth from customers where id = ?";
// 需求不一样,传入的东西不一样
BeanHandler<Connection> handler = new BeanHandler<>(Connection.class);
connection1 = runner.query(connection, sql, handler, 18);
System.out.println(connection1);
} catch (Exception e) {
e.printStackTrace();
}finally {
DruidTest.closeResource1(connection1, null, null);
}
}
}
|