通过JDBC连接数据库的步骤
1、配置XML文件
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
2、导入连接池的druid.ropertise文件(在资源里面有)
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/learning?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
username=root
password=li1579026891
initialSize=5
maxActive=10
maxWait=3000
3、创建工具类(Utils)用来实现druid.properti文件的内容
public class JDBCUtils {
private static DataSource ds = null;
public static DataSource getDs(){
return ds;
}
//druid
static {
Properties pro = new Properties();
try {
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4、使用QueryRunner()获取连接池
Scanner sc = new Scanner(System.in);
QueryRunner qr = new QueryRunner(JDBCUtils.getDs());
5、通过qr对数据库中的表进行增删改查
//query查
qr.query("SELECT * FROM ` goods`;", new BeanListHandler<background.Goods>(background.Goods.class))
//update增删改
qr.update("update ` goods` set count=count-? where id=?", count,key);