MySql驱动(jar包)下载:https://pan.baidu.com/s/19BYnGbO3l5MOOic5K4Ooaw 密码:mwoh
第三方插件(commons-dbutils)下载:https://pan.baidu.com/s/17cyAXHZLgiayx5Y_VHvawQ 密码:6om2
commons-dbutils-1.6.jar---右键---Build Path---Add to Build Path
Demo.java:
package cn.xxx.demo;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import cn.xxx.jdbcutil.JDBCUtilsConfig;
/*
* 使用QueryRunner类,实现对数据表的
* insert delete update
* 调用QueryRunner类的方法 update (Connection con,String sql,Object... param)
* Object...param 可变参数,Object类型;用于替换SQL语句中的?占位符
*/
public class Demo {
private static Connection con = JDBCUtilsConfig.getConnection();
public static void main(String[] args)throws SQLException {
//insert();
delete();
}
public static void delete()throws SQLException{
QueryRunner qr = new QueryRunner(); //创建QueryRunner类对象
String sql = "DELETE FROM sort WHERE sid=?";
int row = qr.update(con, sql, 8); // 执行SQL语句。 第三个参数可以是不定参数Object... ;也可以是单个Object。
System.out.println(row);
DbUtils.closeQuietly(con); // 关闭资源
}
public static void insert()throws SQLException{
QueryRunner qr = new QueryRunner(); //创建QueryRunner类对象
String sql = "INSERT INTO sort (sname,sprice,sdesc)VALUES(?,?,?)";
Object[] params = {"体育用品",289.32,"购买体育用品"}; // 不定长的参数可以用数组传递
int row = qr.update(con, sql, params); // 执行SQL语句
System.out.println(row);
DbUtils.closeQuietly(con); // 关闭资源
}
}
JDBCUtilsConfig.java(自定义的数据库工具类,用于获取数据库连接对象):
package cn.xxx.jdbcutil;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class JDBCUtilsConfig {
private static Connection con ;
private static String driverClass;
private static String url;
private static String username;
private static String password;
static{ // 静态代码块,只会被执行一次
try{
readConfig();
Class.forName(driverClass);
con = DriverManager.getConnection(url, username, password);
}catch(Exception ex){
throw new RuntimeException("数据库连接失败");
}
}
private static void readConfig()throws Exception{
InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);
driverClass=pro.getProperty("driverClass");
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
}
public static Connection getConnection(){
return con;
}
}