封装JDBCUtils工具类。
/**
* @program: HelloWorld
* @description: JDBC工具类
* @author: fish
* @create: 2019-12-07 18:36
**/
public class JDBCUtils {
/**
* @Description: 获取数据库连接
* @Param:
* @return:
* @Author: fish
* @Date: 6:55 PM 2019/12/7
*/
public static Connection getConnection() throws Exception{
Connection conn = null;
//1.读取配置文件中的4个基本信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
conn = DriverManager.getConnection(url,user,password);
return conn;
}
/**
* @Description: 关闭连接和Statement的操作
* @Param:
* @return:
* @Author: fish
* @Date: 6:59 PM 2019/12/7
*/
public static void closeResource(Connection conn, Statement ps){
try {
if (ps!=null)
ps.close();
}catch (SQLException e)
{
e.printStackTrace();
}
try{
if (conn!=null )
conn.close();
}catch (SQLException e)
{
e.printStackTrace();;
}
}
}
实现数据库的修改操作。
public class PreparedStatementUpdateTest {
//修改customers表中的一条记录
@Test
public void testUpdate(){
Connection conn = null;
PreparedStatement ps = null;
try{
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句,返回PreparedStatement的实例
String sql = "update customers set name = ? where id = ?";
ps = conn.prepareStatement(sql);
//3.填充占位符
ps.setObject(1,"莫扎特");
ps.setObject(2,13);
//4.执行
ps.execute();
}catch (Exception e)
{
e.printStackTrace();
}finally {
//5.资源的关闭
JDBCUtils.closeResource(conn,ps);
System.out.println("执行完毕!");
}
}
}
封装通用的增删改操作
//通用的增删改操作
public void update(String sql,Object ...args){//sql中占位符的个数与可变形参的个数相同
Connection conn = null;
PreparedStatement ps = null;
try{
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句,返回PreparedStatement的实例
ps = conn.prepareStatement(sql);
//3.填充占位符
for (int i = 0;i<args.length;i++)
{
ps.setObject(i+1,args[i]);
}
//4.执行
ps.execute();
}catch (Exception e){
e.printStackTrace();
}finally {
//5.资源的关闭
JDBCUtils.closeResource(conn,ps);
System.out.println("执行完毕!");
}
}
public class PreparedStatementUpdateTest {
@Test
public void testCommonUpdate(){
String sql = "delete from customers where id = ?";
update(sql,3);
}
}
数据库中的表名若和数据库关键字相同,则在sql语句中要给表名加``(键盘中1左边的键),如order。否则报错。You have an error in your SQL syntax,check the manual that corresponds to your MySQL server version for the right syntax to use near...
String sql = "update 'order' set order_name = ? where order_id = ?";
update(sql,"DD","2");