EmployeeDao.java
//删除数据
public boolean deleteEmployeeById(int id){
boolean result = false
try{
con = DBCon.getConn()
String sql = "delete from tb_employee where id=?"
pstmt = (PreparedStatement) con.prepareStatement(sql)
pstmt.setInt(1, id)
int i = pstmt.executeUpdate()
if(i == 1)
result = true
}catch(Exception e){
e.printStackTrace()
}finally{
try{
if(pstmt != null){
pstmt.close()
}
}catch(Exception e){
e.printStackTrace()
}
try{
if(con != null){
con.close()
}
}catch(Exception e){
e.printStackTrace()
}
}
return result
}
TestSql2.java
package com.sql.test
import com.sql.dao.EmployeeDao
public class TestSql02 {
public static void main(String[] args){
boolean result = EmployeeDao.getInstance().deleteEmployeeById(1)
if(result == true){
System.out.println("删除成功!")
}else{
System.out.println("删除失败!")
}
}
}
你说的不是很清楚,如果是指定的一条记录的话,只要把username的值加上去就行具体步骤如下:
1.连接数据库。
2.用一个preparestatement预编译下。
3.然后执行把username的值赋给sql语句中的问号
4.执行sql语句
代码如下:
Connection connection = DriverManager,getConnection()
String sql = "delete from 表明 where username = ?"
PreparedStatement preparedStatement = connection.prepareStatement(sql)
preparedStatement.setString(1,"username")
preparedStatement.excute()
报错了就catch下,之后把在finally语句中依次把preparedconnection,connection关闭即可
有问题可追问
使用拼接字符串就行:String sql = "DELETE FROM student WHERE id = '" + id + "'"
但是上述方式存在sql注入风险,
可以使用
perstmt = conn.prepareStatement("DELETE FROM student WHERE id = ?")
perstmt.setString(1,id)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)