依赖:
java
复制代码
<!-- 连接MySQL数据库的依赖,其他数据库网上找pom依赖替换 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- 阿里巴巴连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
DBUntil(工具类)
java
复制代码
public class DBUntil {
private static String url;
private static String name;
private static String password;
private String drive;
private Connection connection;
private Statement statement;
private static DruidDataSource dds;
private static int minPool =10;//最小连接数
private static int maxPool =20;//最大连接数
private static DBUntil DB ;
public static void initPool() {
dds = new DruidDataSource();
dds.setUrl(url);
dds.setUsername(name);
dds.setPassword(password);
dds.setInitialSize(minPool);
dds.setMaxActive(maxPool);
}
public Statement createStatements() {
try {
//Class.forName(drive);
connection = dds.getConnection();
statement = connection.createStatement();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return statement;
}
public PreparedStatement preparedStatement(String sql){
try {
return connection.prepareStatement(sql);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void close() {
dds.close();
}
/*访问器*/
public void setUrl(String url) {this.url = url;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
public void setDrive(String drive) {
this.drive = drive;
}
public void setMinPool(int minPool) {this.minPool = minPool;}
public void setMaxPool(int maxPool) {this.maxPool = maxPool;}
public static DBUntil getDB() {
DB = new DBUntil();
return DB;
}
}
使用:
java
复制代码
private static DBUntil db = DBUntil.getDB();
private static Statement statement;
private String sql;
private PreparedStatement ps;//预编译
static {
db.setUrl("");//数据库url(jdbc:mysql://url:端口/数据库名称?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true)
db.setName("");//用户名
db.setPassword("");//密码
db.initPool();//初始化连接池
/*设置连接数数db.setMinPool();db.setMaxPool();*/
//statement = db.createStatements();
}//初始化
/*在方法中调用 查询为例*/
sql ="SELECT * FROM userinfo WHERE userinfo.username=? AND userinfo.password=?";
try {
ps= db.preparedStatement(sql);
ps.setString(1,username);//将username替代sql第一个问号
ps.setString(2,password);//将username替代sql第二个问号
ResultSet rs= ps.executeQuery();//增删该ps.executeUpdate()
}