
public class Demo {
public static void main(String agrs[]) {
Connection con = null
PreparedStatement pstmt = null
String sql = "delete from user where username=?"
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") //设置数据库连接的驱动
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433databaseName=数据库") //设置数据库连接的 URL,用户名,密码
pstmt = con.prepareStatement(sql)
pstmt.setString(1, "aaa") // 设置SQL语句中username的值
int count = pstmt.executeUpdate()
if (count >0) {
System.out.println(" *** 作成功")
} else {
System.out.println(" *** 作失败")
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
简单实现代码如下: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条)