dbutils是apache封装了JDBC的工具类,比mysql-connector更方便些
下载地址:http://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi
database.properties:
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://192.168.0.207:3306/mydb
user = root
pwd = Console.Write21
package cn.sasa.demo5; import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties; public class DBProperties {
public static String driver = "";
public static String url = "";
public static String user = "";
public static String pwd = ""; static {
// 类的加载器
try {
InputStream input = DBProperties.class.getClassLoader().getResourceAsStream("database.properties");
Properties properties = new Properties();
properties.load(input);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
pwd = properties.getProperty("pwd");
}catch(IOException ex) { }
} public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, pwd);
return conn;
}
}
package cn.sasa.demo5; import java.sql.Connection;
import java.sql.SQLException; import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner; public class QueryRunnerDemo {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn =DBProperties.getConnection(); //创建QueryRunner对象
QueryRunner query = new QueryRunner(); // String sql = "INSERT INTO `product` (`pname`, `price`, `ptype`) VALUES ( ?, ?, ?);";
// Object[] params = {"键盘",100,"计算机配件"};
// int row = query.update(conn, sql, params); String sql = "UPDATE product SET price=? WHERE pid=?";
Object[] params = {222,11};
int row = query.update(conn, sql, params); // String sql = "DELETE FROM product WHERE pid=?";
// int row = query.update(conn, sql, 10); System.out.println(row);
//释放资源
DbUtils.closeQuietly(conn);
}
}