在java中连接数据库后,怎么删除一条记录

在java中连接数据库后,怎么删除一条记录,第1张

你好,我用的是sqlserver2005数据库代码如下:import java.sql.*

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("删除失败!")

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/sjk/6758347.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-27
下一篇2023-03-27

发表评论

登录后才能评论

评论列表(0条)

    保存