189 8069 5689

java删除impl代码 java中impl

java对所有mongodb表进行增删改查表名怎么设置

一、MongoDB数据库参数配置

晋江网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。创新互联公司于2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

1、推荐使用mongodb.cfg.properties配置,则在构造MongoDBService对象的时候只需调用无参构造方法即可自动完成配置。

2、如果没有通过mongodb.cfg.properties,会采用程序指定的默认配置。

// 定义默认配置,1、IP地址 2、端口号 3、用户名 4、密码 5、配置文件位置名 6、数据库名    private static final String MONGODB_ADDRESS = "127.0.0.1";    private static final int MONGODB_PORT = 27017;    private static final String MONGODB_USERNAME = "root";    private static final String MONGODB_PASSWORD = "";    private static final String MONGODB_RESOURCE_FILE = "mongodb.cfg.properties";    private static final String MONGODB_DBNAME = "test";    private static final String MONGODB_COLLECTIONNAME = "test";

3、通过有参构造方法构造MongoDBService对象或通过get/set方法,指定数据库及集合,优先级最高。

//有参构造方法,指定数据库名与集合名    public MongoDBServiceImpl(String dbName, String collName) {        this.dbName = dbName;        this.collName = collName;        try {            db = getDb();        } catch (Throwable e) {            e.printStackTrace();        }    }    //无参构造方法,返回配置文件配置的数据库对象引用,如果配置文件中没有设置则返回默认数据库对象引用    public MongoDBServiceImpl() {        getDb();    }    /*     * 获取数据库对象,3种情况(优先级从高到低):span style="white-space: pre" /span *1、构造方法指定2、配置文件指定3、默认数据库span style="white-space: pre" /span *(情况2、3在MongoDButil中设置)     */    public DB getDb() {        if (this.db == null) {            if (this.dbName == null) {                this.db = MongoDBUtil.getDB();            } else {                this.db = MongoDBUtil.getDBByName(this.dbName);            }        }        return this.db;    }         /*     * 获取集合对象,3种情况(优先级从高到低):         *1、构造方法指定2、配置文件指定3、默认数据库     *(情况2、3在MongoDButil中设置)     */    public DBCollection getCollection() {        if(this.collName != null){            return db.getCollection(this.collName);        }        else {            return MongoDBUtil.getDBCollection();        }    }

二、方法简介(具体实现参看MongoDBServiceImpl接口实现类)

1、获取基本信息或对象:

(1)、获取数据库名: getDbName()

(2)、设置数据库名(指定数据库): setDbName(String dbName)

(3)、获取集合名: getCollName()

(4)、设置集合名(指定集合): setCollName(String collName)

(5)、获取数据库对象: getDb()

2、数据插入方式:

(1)、插入单条数据: insert(DBObject obj)

(2)、插入多条数据: insertBatch(List list)void

3、数据删除方式:

(1)、删除单条数据: delete(DBObject obj)

(2)、删除多条数据: deleteBatch(List list)

4、数量统计方式:

(1)、获取集合中数据数量: getCollectionCount()

(2)、获取符合条件的数据数量: getCount(DBObject obj)

5、查找数据:

(1)、查找所有数据: findAll()

(2)、查找符合条件的数据: find(DBObject obj)

(3)、查找符合条件的数据并排序: find(DBObject query, DBObject sort)

(4)、查找符合条件的指定数量的数据并排序:find(DBObject query, DBObject sort, int start, int limit)

(5)、由ID查找数据: getById(String id)

6、更新数据 :update(DBObject setFields, DBObject whereFields) void

7、打印List: printListDBObj(List list)

测试代码:(@Test)

public class testMongoService {    //使用mongodb.cfg.properties中配置的数据库与集合,如未指定,使用MongoDBUtil中默认的数据库与集合    MongoDBService mongoDBService1 = new MongoDBServiceImpl();         //测试插入数据    @Test    public void testInsert(){        //数据一,包括用户名、密码,地址信息(省份、城市),爱好[…]        BasicDBList dbList1 = new BasicDBList();        dbList1.add("basketball");        dbList1.add("music");        dbList1.add("web");        DBObject dbObject1 = new BasicDBObject("username","insert1")            .append("age", 18)            .append("address", new BasicDBObject("province","广东").append("city", "广州"))            .append("favourite", dbList1);        //数据二        BasicDBList dbList2 = new BasicDBList();        dbList2.add("football");        dbList2.add("music");        DBObject dbObject2 = new BasicDBObject("username","insert2")            .append("age", 18)            .append("address", new BasicDBObject("province","陕西").append("city", "西安"))            .append("favourite", dbList2);        //数据三        BasicDBList dbList3 = new BasicDBList();        dbList3.add("Linux");        DBObject dbObject3 = new BasicDBObject("username","insert3")            .append("age", 18)            .append("address", new BasicDBObject("province","河北").append("city", "保定"))            .append("favourite", dbList3);        //数据四        BasicDBList dbList4 = new BasicDBList();        dbList4.add("swim");        dbList4.add("android");        DBObject dbObject4 = new BasicDBObject("username","insert4")            .append("age", 18)            .append("address", new BasicDBObject("province","四川").append("city", "成都"))            .append("favourite", dbList4);        //数据五        DBObject dbObject5 = new BasicDBObject("username", "insert5")            .append("age", 28)            .append("address", new BasicDBObject("city", "杭州"));        mongoDBService1.printListDBObj(mongoDBService1.findAll());        System.out.println("——————————————————insert collection——————————————————");        Listdbobject list = new ArrayListdbobject();        list.add(dbObject1);        list.add(dbObject2);        list.add(dbObject3);        list.add(dbObject5);        mongoDBService1.insertBatch(list);        System.out.println("——————————————————insert one——————————————————");        mongoDBService1.insert(dbObject4);        mongoDBService1.printListDBObj(mongoDBService1.findAll());    }         //测试查询数据    @Test    public void testFind(){        DBObject dbObject = new BasicDBObject("username","insert1");        System.out.println("数量:" + mongoDBService1.getCollectionCount());        System.out.println("username=java的数据数量:" + mongoDBService1.getCount(dbObject));        System.out.println("——————————————————find all——————————————————");        mongoDBService1.printListDBObj(mongoDBService1.findAll());        System.out.println("——————————————————find obj——————————————————");        mongoDBService1.printListDBObj(mongoDBService1.find(dbObject));        System.out.println("——————————————————find sort——————————————————");        mongoDBService1.printListDBObj(mongoDBService1.find(new BasicDBObject(), new BasicDBObject("age", 1)));        System.out.println("——————————————————find sort limit——————————————————");        mongoDBService1.printListDBObj(mongoDBService1.find(new BasicDBObject(), new BasicDBObject("age", 1), 1, 2));    }     //测试数据更新    @Test    public void testUpdate(){        BasicDBObject newDocument = new BasicDBObject("$set",new BasicDBObject("age",11));                         BasicDBObject searchQuery = new BasicDBObject().append("username", "insert2");             mongoDBService1.printListDBObj(mongoDBService1.find(searchQuery));        System.out.println("——————————————————update——————————————————");        mongoDBService1.update(newDocument, searchQuery);        mongoDBService1.printListDBObj(mongoDBService1.find(searchQuery));    }         //测试数据删除    @Test    public void testDelete(){        DBObject dbObject1 = new BasicDBObject("username", "insert1");        DBObject dbObject2 = new BasicDBObject("username", "insert2");        DBObject dbObject3 = new BasicDBObject("username", "insert3");        DBObject dbObject4 = new BasicDBObject("username", "insert4");        DBObject dbObject5 = new BasicDBObject("username", "insert5");        Listdbobject list = new ArrayListdbobject();        list.add(dbObject1);        list.add(dbObject2);        list.add(dbObject3);        list.add(dbObject4);        mongoDBService1.printListDBObj(mongoDBService1.findAll());        System.out.println("——————————————————delete list——————————————————");        mongoDBService1.deleteBatch(list);        System.out.println("——————————————————delete one——————————————————");        mongoDBService1.delete(dbObject5);        //System.out.println("——————————————————delete all——————————————————");        //mongoDBService1.delete(new BasicDBObject());        mongoDBService1.printListDBObj(mongoDBService1.findAll());    }}/dbobject/dbobject/dbobject/dbobject

测试结果:

源代码:(完整项目文件下载链接:点击打开链接)

MongoDBServiceImpl.java

public class MongoDBServiceImpl implements MongoDBService {    private String dbName;    private String collName;    private DB db;         //有参构造方法,指定数据库名与集合名    public MongoDBServiceImpl(String dbName, String collName) {        this.dbName = dbName;        this.collName = collName;        try {            db = getDb();        } catch (Throwable e) {            e.printStackTrace();        }    }    //无参构造方法,返回配置文件配置的数据库对象引用,如果配置文件中没有设置则返回默认数据库对象引用    public MongoDBServiceImpl() {        getDb();    }    /*     * 获取数据库对象,3种情况(优先级从高到低):     *1、构造方法指定2、配置文件指定3、默认数据库     *(情况2、3在MongoDButil中设置)     */    public DB getDb() {        if (this.db == null) {            if (this.dbName == null) {                this.db = MongoDBUtil.getDB();            } else {                this.db = MongoDBUtil.getDBByName(this.dbName);            }        }        return this.db;    }         /*     * 获取集合对象,3种情况(优先级从高到低):     *1、构造方法指定2、配置文件指定3、默认数据库     *(情况2、3在MongoDButil中设置)     */    public DBCollection getCollection() {        if(this.collName != null){            return db.getCollection(this.collName);        }        else {            return MongoDBUtil.getDBCollection();        }    }     public DBObject map2Obj(Mapstring, object="" map) {        DBObject obj = new BasicDBObject();        if (map.containsKey("class") map.get("class") instanceof Class)            map.remove("class");        obj.putAll(map);        return obj;    }    //插入数据    public void insert(DBObject obj) {        getCollection().insert(obj);    }    //插入多条数据    public void insertBatch(Listdbobject list) {        if (list == null || list.isEmpty()) {            return;        }        Listdbobject listDB = new ArrayListdbobject();        for (int i = 0; i list.size(); i++) {            listDB.add(list.get(i));        }        getCollection().insert(listDB);    }    //删除数据    public void delete(DBObject obj) {        getCollection().remove(obj);    }    //删除多条数据    public void deleteBatch(Listdbobject list) {        if (list == null || list.isEmpty()) {            return;        }        for (int i = 0; i list.size(); i++) {            getCollection().remove(list.get(i));        }    }    //获取集合中的数据数量    public long getCollectionCount() {        return getCollection().getCount();    }    //查找符合条件的数据数量    public long getCount(DBObject obj) {        if (obj != null)            return getCollection().getCount(obj);        return getCollectionCount();    }    //查找符合条件的数据    public Listdbobject find(DBObject obj) {        DBCursor cur = getCollection().find(obj);        return DBCursor2list(cur);    }         //查找符合条件的数据并排序    @Override    public Listdbobject find(DBObject query, DBObject sort) {        DBCursor cur;        if (query != null) {            cur = getCollection().find(query);        } else {            cur = getCollection().find();        }        if (sort != null) {            cur.sort(sort);        }        return DBCursor2list(cur);    }     //查找符合条件的数据并排序,规定数据个数    @Override    public Listdbobject find(DBObject query, DBObject sort, int start,            int limit) {        DBCursor cur;        if (query != null) {            cur = getCollection().find(query);        } else {            cur = getCollection().find();        }        if (sort != null) {            cur.sort(sort);        }        if (start == 0) {            cur.batchSize(limit);        } else {            cur.skip(start).limit(limit);        }        return DBCursor2list(cur);    }         //将DBCursor转化为listdbobject    private Listdbobject DBCursor2list(DBCursor cur) {        Listdbobject list = new ArrayListdbobject();        if (cur != null) {            list = cur.toArray();        }        return list;    }     //更新数据    public void update(DBObject setFields, DBObject whereFields) {        getCollection().updateMulti(whereFields, setFields);    }    //查询集合中所有数据    public Listdbobject findAll() {        DBCursor cur = getCollection().find();        Listdbobject list = new ArrayListdbobject();        if (cur != null) {            list = cur.toArray();        }        return list;    }     //由ID获取数据    public DBObject getById(String id) {        DBObject obj = new BasicDBObject();        obj.put("_id", new ObjectId(id));        DBObject result = getCollection().findOne(obj);        return result;    }     public String getDbName() {        return dbName;    }     public void setDbName(String dbName) {        this.dbName = dbName;        this.db = MongoDBUtil.getDBByName(this.dbName);    }     public String getCollName() {        return collName;    }     public void setCollName(String collName) {        this.collName = collName;    }    @Override    public void printListDBObj(Listdbobject list) {        // TODO Auto-generated method stub        for(DBObject dbObject: list){            System.out.println(dbObject);        }    }       }/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/dbobject/string,

MongoDBUtil.java

public class MongoDBUtil {    // 定义默认配置,1、IP地址 2、端口号 3、用户名 4、密码 5、配置文件位置名 6、数据库名    private static final String MONGODB_ADDRESS = "127.0.0.1";    private static final int MONGODB_PORT = 27017;    private static final String MONGODB_USERNAME = "root";    private static final String MONGODB_PASSWORD = "";    private static final String MONGODB_RESOURCE_FILE = "mongodb.cfg.properties";    private static final String MONGODB_DBNAME = "test";    private static final String MONGODB_COLLECTIONNAME = "test";    // 定义静态变量,1、Mongo对象(代表数据库连接)2、DB对象(代表数据库)3、集合名4、数据库相关配置映射集合5、已获取的数据库连接    private static Mongo mongo;    private static DB db;    private static DBCollection collection;    private static Mapstring, string="" cfgMap = new HashMapstring, string=""();    private static Hashtablestring, db="" mongoDBs = new Hashtablestring, db=""();     /**     * 初始化Mongo的数据库     */    static {        init();    }     /**     * 获取配置文件中配置的DB对象     */    public static DB getDB() {        return db;    }     /**     * 获取配置文件中配置的DBCollection对象     */    public static DBCollection getDBCollection() {        return collection;    }     /**     * 根据数据库名称,得到数据库 如果不存在,则创建一个该名称的数据库,并设置用户名和密码为配置文件中的参数值     *     * @param dbName     * @return DB     */    @SuppressWarnings("deprecation")    public static DB getDBByName(String dbName) {        DB db = mongo.getDB(dbName);        if (!mongoDBs.contains(db)) {            System.out.println("add");            db.addUser(cfgMap.get("mongo.db.username"),                    cfgMap.get("mongo.db.password").toCharArray());            mongoDBs.put(dbName, db);        }        return db;    }     // ————————————————————————————————————初始化过程————————————————————————————————————    /**     * 获取配置文件mongedb.cfg.properties的文件对象     */    public static File getConfigFile() {        String path = MongoDBUtil.class.getResource("/").getPath();        String fileName = path + MONGODB_RESOURCE_FILE;        System.out.println(fileName);        File file = new File(fileName);        if (file.exists()) {            return file;        }        return null;    }     /**     * 通过mongedb.cfg.properties配置文件初始化配置映射集合,如果没有编写配置文件,则加载程序指定的默认配置     */    @SuppressWarnings("unchecked")    private static void initCfgMap() {        File file = getConfigFile();        if (file != null) {            Properties p = new Properties();            try {                p.load(new FileInputStream(file));                for (Enumeration enu = p.propertyNames(); enu.hasMoreElements();) {                    String key = (String) enu.nextElement();                    String value = (String) p.getProperty(key);                    cfgMap.put(key, value);                }            } catch (IOException e) {                System.out.println("加载Mongo配置文件失败!");                e.printStackTrace();            }        } else { // 如果没有编写配置文件,则加载默认配置            cfgMap.put("mongo.db.address", MONGODB_ADDRESS);            cfgMap.put("mongo.db.port", String.valueOf(MONGODB_PORT));            cfgMap.put("mongo.db.username", MONGODB_USERNAME);            cfgMap.put("mongo.db.password", MONGODB_PASSWORD);            cfgMap.put("mongo.db.dbname", MONGODB_DBNAME);            cfgMap.put("mongo.db.collectionname", MONGODB_COLLECTIONNAME);        }    }     /**     * 初始化Mongo的数据库(将db指向相应对象引用,将collection指向相应对象引用,通过mongoDBs记录现有数据库对象)     */    @SuppressWarnings("deprecation")    private static void init() {        initCfgMap();        try {            String address = cfgMap.get("mongo.db.address");            int port = Integer.parseInt(cfgMap.get("mongo.db.port").toString());            String dbName = cfgMap.get("mongo.db.dbname");            String username = cfgMap.get("mongo.db.username");            String password = cfgMap.get("mongo.db.password");            String collectionName = cfgMap.get("mongo.db.collectionname");            mongo = new Mongo(address, port);            if (dbName != null !"".equals(dbName)) {                db = mongo.getDB(dbName);                if (username != null !"".equals(username)) {                    db.addUser(username, password.toCharArray());                    if (collectionName != null !"".equals(collectionName)) {                        collection = db.getCollection(collectionName);                    }                }                mongoDBs.put(dbName, db);            }        } catch (Exception e) {            e.printStackTrace();        }    } }

关于java 连接数据库实现增删改查的具体功能代码。

首先你得确定你的数据库连接是通过什么形式连接的,hibernate还是原生态的jdbc 还是spring;

如果是只有hibernate,那么你得通过加载配置文件得到sessionFactory,然后得到session

如果spring,那么同样也需要注入sessionfactory到你的dao

如果是jdbc方式,那么你就按照原生态jdbc写法

总之,在你构造DAO时,得有数据源。这样才能操纵你的数据库

如果搞懂了这些问题,那么你的第一个,第三个问题就迎刃而解了。至于第二问题,我没明白你什么意思!

处理删除操作时出现 Unknown entity: java.lang.Integer

看一下--------SubjectAction

public String deleteSubject(){

isubjectbiz.deleteSubject(subjectId);

return SUCCESS;

}

subjectId 是否是用struts2 自动从页面封装过来的 还是你使用request获取的 首先你输出一下有没有值 然后如果是request获取的 必须要把它转换成integer 其次如果有值 且为integer 这时你就要检查你的数据库隐射文件是否正确 一级一级排除

JAVA 实现数据库增删改查的Dao和DaoImpl的写法

package org.dao;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.util.Date;

import org.dbc.DBManageer;

import org.dbc.DBUtil;

import org.vo.CardInfo;

public class CardInfoDao {

public void testResultSetMetaData() {

String sql = "select * from cardinfo";

Connection con = new DBUtil().getConnection();

PreparedStatement ps = null;

ResultSetMetaData rsmd = null;

ResultSet rs = null;

try {

ps = con.prepareStatement(sql);

rs = ps.executeQuery();

rsmd = rs.getMetaData();

for (int i = 1; i rsmd.getColumnCount(); i++) {

System.out.print(" 数据类型名:" + rsmd.getColumnClassName(i));

System.out.print(" 别名:" + rsmd.getColumnLabel(i));

System.out.print(" 列名:" + rsmd.getColumnName(i));

System.out.print(" 数据类型:" + rsmd.getColumnTypeName(i));

System.out.println(" 数据类型:" + rsmd.getColumnType(i));

}

while (rs.next()) {

// 通过反射可以对VO对象(CardInfo)自动赋值

// for(...)

// CardInfo ci=new CardInfo();

// ci.setId(rs.getInt(columnIndex))

/*

* CardInfo ca = new CardInfo(); Class cc = ca.getClass();

*/

/*Class? c = Class.forName("org.vo.CardInfo");

CardInfo ca = (CardInfo) c.newInstance();

ca.setCardId(rs.getString("cardId"));

ca.setCustomerName(rs.getString("customerName"));

ca.setCurrentMoney(rs.getFloat("currentMoney"));

ca.setOpenDate(rs.getDate("openDate"));

System.out.println(ca);//ok */

//加载一个CardInfo类

Class c = Class.forName("org.vo.CardInfo");

Object o = c.newInstance(); //获得它的一个实例

//定义String类的对象数组

Class[] params = new Class[] { String.class};

//定义float类的对象数组

Class[] floatparams = new Class[] { float.class};

//定义Date(util)类的对象数组

Class[] dateparams = new Class[] { Date.class};

//获得setCardId方法

Method me = c.getMethod("setCardId", params);

//实例方法的参数

Object []ostr = new Object[]{rs.getString("cardId")};

//如果底层方法是静态的,那么可以忽略指定的 obj 参数。该参数可以为 null。

//如果底层方法所需的形参数为 0,则所提供的 args 数组长度可以为 0 或 null。

//o 调用方法的对象 ostr 方法调用的参数

me.invoke(o, ostr);

//获得setCustomerName方法

Method name = c.getMethod("setCustomerName", params);

Object []cusname = new Object[]{rs.getString("customerName")};

name.invoke(o,cusname);

//获得setCurrentMoney方法

Method money = c.getMethod("setCurrentMoney", floatparams);

Object []cusmoney = new Object[]{rs.getFloat("currentMoney")};

money.invoke(o,cusmoney);

//获得setOpenDate方法

Method date = c.getMethod("setOpenDate",dateparams);

Object []openDate = new Object[]{rs.getDate("openDate")};

date.invoke(o, openDate);

//打印

System.out.println(o);

}

} catch (SQLException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (SecurityException e) {

e.printStackTrace();

}catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (NoSuchMethodException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

}

public void showResultSet() {

String sql = "select * from cardinfo";

Connection con = new DBManageer().getConnection();

PreparedStatement ps = null;

try {

ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

ResultSet rs = ps.executeQuery();

System.out.println("---依次读取------");

while (rs.next()) {

CardInfo ca = new CardInfo();

ca.setCardId(rs.getString("cardId"));

ca.setCustomerName(rs.getString("customerName"));

ca.setCurrentMoney(rs.getFloat("currentMoney"));

ca.setOpenDate(rs.getDate("openDate"));

System.out.println(ca);

}

System.out.println("---倒读------");

while (rs.previous()) {

CardInfo ca = new CardInfo();

ca.setCardId(rs.getString("cardId"));

ca.setCustomerName(rs.getString("customerName"));

ca.setCurrentMoney(rs.getFloat("currentMoney"));

ca.setOpenDate(rs.getDate("openDate"));

System.out.println(ca);

}

rs.absolute(3);// 定位倒第几行

rs.updateString("customerName", "star");

// rs.updateRow();

rs.beforeFirst();

while (rs.next()) {

CardInfo ca = new CardInfo();

ca.setCardId(rs.getString("cardId"));

ca.setCustomerName(rs.getString("customerName"));

ca.setCurrentMoney(rs.getFloat("currentMoney"));

ca.setOpenDate(rs.getDate("openDate"));

System.out.println(ca);

}

} catch (SQLException e) {

e.printStackTrace();

}

}

}

java如何实现对数据表里面的数据删除(最好给个具体代码范例)

连接数据库

public class DBManager {

//定义数据库连接的URL

private static final String URL="jdbc:sqlserver://localhost:1433;database=j1105";

//定义数据库的用户名

private static final String USERNAME = "sa";

//定义数据库密码

private static final String PASSWORD = "sa";

//定义一个连接的引用,使用单例模式

private static Connection conn = null;

//使用静态块来注册驱动

//类加载时自动执行代码块

static {

//反射com.microsoft.sqlserver.jdbc.SQLServerDriver.class

try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

//获得连接

//在程序使用过程中始终只有1个对象存在

//使用单例模式来给Connection赋值

public static Connection getConnection(){

if(conn == null){

try {

conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

} catch (SQLException e) {

e.printStackTrace();

}

}

return conn;

}

/**

* 关闭的一些操作 , 优化

* @param conn

* @param stat

* @param rs

*/

public static void close(Connection conn,Statement stat,ResultSet rs){

try{

if(conn != null){

conn.close();

}

if(stat != null){

stat.close();

}

if(rs != null){

rs.close();

}

}catch(SQLException e){

e.printStackTrace();

}

}

/**

* 重写上面的方法,在只有2个参数的情况下关闭

* @param conn

* @param stat

*/

public static void close(Connection conn,Statement stat){

try{

if(conn != null){

conn.close();

}

if(stat != null){

stat.close();

}

}catch(SQLException e){

e.printStackTrace();

}

}

public static void main(String[] args){

Connection conn = DBManager .getConnection();

System.out.println(conn);

}

}

接口

public interface IStudentDao {

public void deleteStudent(int xh);

}

实现

public class StudentDAOimpl implements IStudentDao {

public void deleteStudent(int xh) {

try{

String sql = "delete from tb_student where xh = ?";

PreparedStatement ps = conn.prepareStatement(sql);

ps.setInt(1, xh);

ps.executeUpdate();

System.out.println("成功删除");

}catch(SQLException e){

e.printStackTrace();

}

}

}


标题名称:java删除impl代码 java中impl
URL地址:http://cdxtjz.cn/article/hpeoec.html

其他资讯