
ps.setInt(1, sid)
//需要一个值来接收这个sid
//这个sid是用户或者管理员输入的值
//然后运行sql
Java连接数据库,要删除指定行的信息,可以使用delete语句,传入某行的参数,示例如下:
public class Update1 {public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")//加载SQL SERVER数据库
Connection con = DriverManager.getConnection("jdbc:odbc:tt", "sa", "www")//连接数据库
String sq="delete from t1 where userName=?"//删除指定行
PreparedStatement ps = con.prepareStatement(sq)
ps.setString(1, "cct")
int t = ps.executeUpdate()
if (t > 0) {//判断是否删除成功
System.out.println("ok")
} else {
System.out.println("false")
}
ps.close()
con.close()
}
}
简单实现代码如下: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("删除失败!")
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)