java在access数据库下实现增删改查

java在access数据库下实现增删改查,第1张

import javasql;

public class Main

{

public static void main(String[] args) throws ClassNotFoundException {

Connection con;

Statement sql;

ResultSet rs;

con = null;

try {

String ur1="jdbc:odbc:Driver={Microsoft Access Driver (mdb)};DBQ=C:/myfile/qfcmdb";

ClassforName("sunjdbcodbcJdbcOdbcDriver");

con = DriverManagergetConnection(ur1);

sql= concreateStatement(ResultSetTYPE_SCROLL_INSENSITIVE,ResultSetCONCUR_UPDATABLE);

rs = sqlexecuteQuery("select from 设备号'");

//这里是查询语句,如果需要做CRUD,换成对应的sql语句就行了。

while (rsnext()) {

String user = rsgetString("设备号");

Systemoutprintln(user);

}

} catch (Exception e) {

Systemoutprintln("sql出错:");

Systemoutprintln(e);

}

}

}

package comly520db;

import javasqlConnection;

import javasqlDriverManager;

import javasqlPreparedStatement;

import javasqlResultSet;

import javasqlResultSetMetaData;

import javasqlSQLException;

import javasqlStatement;

import javautilEnumeration;

import javautilHashtable;

import javautilList;

import javautilVector;

import javaxnamingContext;

import javaxnamingInitialContext;

import javaxsqlDataSource;

/

mysql数据 *** 作类。

@author Ryoma

/

public class MySqlOperate implements SqlOperate {

private Connection con;

private String DBname;

private String sql;

/

Mysql数据库初始化包名

/

private String INIT_SQL_CTX = "orggjtmmmysqlDriver";

/

MYSQL数据库服务参数:服务器IP地址和端口

/

private String SQL_SERVICE = "jdbc:mysql://127001:3306autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8";

/

MYSQL数据库参数:系统管理用户

/

private String SQL_SYSTEM_USER = "root";

/

MYSQL数据库参数:系统管理密码

/

private String SQL_SYSTEM_PASSWORD = "123456";

/

初始化链接方法。此方法不需要再使用use Dbname;

/

public MySqlOperate() {

try {

Context ctx = new InitialContext();

if (ctx == null)

throw new Exception("Boom - No Context");

// java:comp/env/jdbc/imabled_mysql 为配置的连接池的jndi名称。

DataSource ds = (DataSource) ctx

lookup("java:comp/env/jdbc/imabled_mysql");

con = dsgetConnection();

} catch (Exception ex) {

exprintStackTrace();

}

}

/

指定库名的连接方法,此方法没有使用连接池,不赞成使用。

@param DBn

/

public MySqlOperate(String DBn) {

try {

ClassforName(thisINIT_SQL_CTX);

} catch (javalangClassNotFoundException e) {

eprintStackTrace();

}

try {

con = DriverManagergetConnection(thisSQL_SERVICE + "/" + DBn,

thisSQL_SYSTEM_USER, thisSQL_SYSTEM_PASSWORD);

DBname = DBn;

} catch (SQLException ex) {

exprintStackTrace();

}

}

public boolean add(String tablename, Hashtable searchdetail) {

Statement stmt = null;

Enumeration key_values = searchdetailkeys();

String key, value;

String temp = (String) key_valuesnextElement();

key = temp;

value = "'" + searchdetailget(temp) + "'";

while (key_valueshasMoreElements()) {

temp = (String) key_valuesnextElement();

key = key + "," + temp;

value = value + "," + "'" + searchdetailget(temp) + "'";

}

try {

useDB();

stmt = concreateStatement();

sql = "insert into " + tablename + " (" + key + ") " + " VALUES ("

+ value + ")";

stmtexecuteUpdate(sql);

return true;

} catch (SQLException ex) {

Systemoutprintln("执行的出错的sql语句:" + sql);

exprintStackTrace();

return false;

} finally {

closeStmt(stmt);

}

}

public boolean batchImport(String tablename, List list, String[] fields)

throws SQLException {

PreparedStatement ps = null;

String key, value;

key = toString(fields);

String[] values = new String[fieldslength];

for (int i = 0; i < valueslength; i++) {

values[i] = "";

}

value = toString(values);

try {

useDB();

consetAutoCommit(false);

Systemoutprintln("insert into " + tablename + " (" + key + ") "

+ " VALUES (" + value + ")");

ps = conprepareStatement("insert into " + tablename + " (" + key

+ ") " + " VALUES (" + value + ")");

String[] tmpData = null;

for (int i = 0; i < listsize(); i++) {

tmpData = (String[]) listget(i);

for (int j = 0; j < fieldslength && j < tmpDatalength; j++) {

pssetString(j + 1, tmpData[j]);

}

psaddBatch();// 添加执行的语句。

}

int[] count = psexecuteBatch();// 批量执行

concommit();

return true;

} catch (SQLException ex) {

throw ex;

} finally {

try {

if (ps != null) {

psclearParameters();

psclose();

ps = null;

}

} catch (SQLException e) {

throw e;

}

}

}

public boolean delete(String tablename, String filter) {

Statement stmt = null;

String value;

try {

useDB();

stmt = concreateStatement();

sql = "delete from " + tablename + " where " + filter;

stmtexecuteUpdate(sql);

return true;

} catch (SQLException e) {

Systemoutprintln("执行的出错的sql语句:" + sql);

eprintStackTrace();

return false;

} finally {

closeStmt(stmt);

}

}

public Hashtable list(String sql) {

Hashtable[] infoList = search(sql);

if (infoList == null || infoListlength < 1)

return null;

return infoList[0];

}

public Hashtable list(String tablename, String id) {

String sql = "select from " + tablename + " where id ='" + id + "'";

return list(sql);

}

public boolean modify(String tablename, Hashtable setdetail, String filter) {

Enumeration key_values = setdetailkeys();

Statement stmt = null;

String value;

String temp = (String) key_valuesnextElement();

value = temp + "='" + setdetailget(temp) + "'";

while (key_valueshasMoreElements()) {

temp = (String) key_valuesnextElement();

value = value + "," + temp + "='" + setdetailget(temp) + "'";

}

try {

useDB();

stmt = concreateStatement();

sql = "update " + tablename + " set " + value + " where " + filter;

int tag = stmtexecuteUpdate(sql);

if (tag == 0)

return false;

else

return true;

} catch (SQLException e) {

Systemoutprintln("执行的出错的sql语句:" + sql);

eprintStackTrace();

return false;

} finally {

closeStmt(stmt);

}

}

public Hashtable[] search(String sql) {

ResultSet rs;

Statement stmt = null;

try {

useDB();

stmt = concreateStatement();

rs = stmtexecuteQuery(sql);

return toHashtableArray(rs);

} catch (SQLException ex) {

Systemoutprintln("执行的出错的sql语句:" + sql);

exprintStackTrace();

return null;

} finally {

closeStmt(stmt);

}

}

public Hashtable[] search(String tablename, String[] fieldname,

String filter) {

return search(tablename, fieldname, filter, "");

}

public Hashtable[] search(String tablename, String[] fieldname,

String filter, String ordergroup) {

ResultSet rs;

Statement stmt = null;

String colname = fieldname[0];

for (int i = 1; i < fieldnamelength; i++) {

colname += "," + fieldname[i];

}

String queryString = "select " + colname + " from " + tablename;

if (!filterequals("")) {

queryString = queryString + " where " + filter;

}

if (!ordergroupequals("")) {

queryString = queryString + " " + ordergroup;

}

return search(sql);

}

/

@return the con

/

public Connection getCon() {

return con;

}

public void close() {

try {

if (con != null)

conclose();

} catch (SQLException e) {

eprintStackTrace();

}

}

/

返回使用的数据库

@return the dBname

/

public String getDBname() {

return DBname;

}

/

设置使用的数据库

@param bname

the dBname to set

/

public void setDBname(String bname) {

DBname = bname;

}

/

返回执行的sql语句

@return the sql

/

public String getSql() {

return sql;

}

/

本方法是为了再没有使用连接池的情况下,首先选择使用的数据库。

/

private void useDB() {

if (DBname != null && DBnameequals("")) {

String query = "use " + DBname;

Statement stmt = null;

try {

stmt = concreateStatement();

stmtexecute(query);

} catch (SQLException e) {

eprintStackTrace();

} finally {

if (stmt != null) {

try {

stmtclose();

} catch (SQLException e) {

eprintStackTrace();

}

}

}

}

}

/

关闭Statement

@param stmt

/

private void closeStmt(Statement stmt) {

if (stmt != null) {

try {

stmtclose();

} catch (SQLException e) {

eprintStackTrace();

}

}

}

/

@param ss

@return

/

private String toString(String[] ss) {

String s = "";

for (int i = 0; i < sslength; i++) {

s += ss[i] + ",";

}

if (sendsWith(","))

s = ssubstring(0, slength() - 1);

return s;

}

/

把ResultSet转换成Hashtable数组 javautilArraysasList 可以把数组转换成List

@param rs

@return

/

private Hashtable[] toHashtableArray(ResultSet rs) {

Vector searchresult = new Vector();

try {

ResultSetMetaData rsmd = rsgetMetaData();

int column = rsmdgetColumnCount();

while (rsnext()) {

Hashtable onerow = new Hashtable();

for (int i = 1; i <= column; i++) {

try {

String columnName = rsmdgetColumnName(i);

String columnValue = rsgetString(columnName);

onerowput(columnName, columnValue);

} catch (Exception e) {

}

}

searchresultadd(onerow);

}

Hashtable[] searchset = new Hashtable[searchresultsize()];

searchresulttoArray(searchset);

return searchset;

} catch (SQLException e) {

eprintStackTrace();

return null;

}

}

}

一、MongoDB数据库参数配置

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

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

// 定义默认配置,1、IP地址 2、端口号 3、用户名 4、密码 5、配置文件位置名 6、数据库名    private static final String MONGODB_ADDRESS = "127001";    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 = "mongodbcfgproperties";    private static final String MONGODB_DBNAME = "test";    private static final String MONGODB_COLLECTIONNAME = "test";

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

//有参构造方法,指定数据库名与集合名    public MongoDBServiceImpl(String dbName, String collName) {        thisdbName = dbName;        thiscollName = collName;        try {            db = getDb();        } catch (Throwable e) {            eprintStackTrace();        }    }    //无参构造方法,返回配置文件配置的数据库对象引用,如果配置文件中没有设置则返回默认数据库对象引用    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 (thisdb == null) {            if (thisdbName == null) {                thisdb = MongoDBUtilgetDB();            } else {                thisdb = MongoDBUtilgetDBByName(thisdbName);            }        }        return thisdb;    }         /      获取集合对象,3种情况(优先级从高到低):         1、构造方法指定2、配置文件指定3、默认数据库     (情况2、3在MongoDButil中设置)     /    public DBCollection getCollection() {        if(thiscollName != null){            return dbgetCollection(thiscollName);        }        else {            return MongoDBUtilgetDBCollection();        }    }

二、方法简介(具体实现参看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 {    //使用mongodbcfgproperties中配置的数据库与集合,如未指定,使用MongoDBUtil中默认的数据库与集合    MongoDBService mongoDBService1 = new MongoDBServiceImpl();         //测试插入数据    @Test    public void testInsert(){        //数据一,包括用户名、密码,地址信息(省份、城市),爱好[…]        BasicDBList dbList1 = new BasicDBList();        dbList1add("basketball");        dbList1add("music");        dbList1add("web");        DBObject dbObject1 = new BasicDBObject("username","insert1")            append("age", 18)            append("address", new BasicDBObject("province","广东")append("city", "广州"))            append("favourite", dbList1);        //数据二        BasicDBList dbList2 = new BasicDBList();        dbList2add("football");        dbList2add("music");        DBObject dbObject2 = new BasicDBObject("username","insert2")            append("age", 18)            append("address", new BasicDBObject("province","陕西")append("city", "西安"))            append("favourite", dbList2);        //数据三        BasicDBList dbList3 = new BasicDBList();        dbList3add("Linux");        DBObject dbObject3 = new BasicDBObject("username","insert3")            append("age", 18)            append("address", new BasicDBObject("province","河北")append("city", "保定"))            append("favourite", dbList3);        //数据四        BasicDBList dbList4 = new BasicDBList();        dbList4add("swim");        dbList4add("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", "杭州"));        mongoDBService1printListDBObj(mongoDBService1findAll());        Systemoutprintln("——————————————————insert collection——————————————————");        List<dbobject> list = new ArrayList<dbobject>();        listadd(dbObject1);        listadd(dbObject2);        listadd(dbObject3);        listadd(dbObject5);        mongoDBService1insertBatch(list);        Systemoutprintln("——————————————————insert one——————————————————");        mongoDBService1insert(dbObject4);        mongoDBService1printListDBObj(mongoDBService1findAll());    }         //测试查询数据    @Test    public void testFind(){        DBObject dbObject = new BasicDBObject("username","insert1");        Systemoutprintln("数量:" + mongoDBService1getCollectionCount());        Systemoutprintln("username=java的数据数量:" + mongoDBService1getCount(dbObject));        Systemoutprintln("——————————————————find all——————————————————");        mongoDBService1printListDBObj(mongoDBService1findAll());        Systemoutprintln("——————————————————find obj——————————————————");        mongoDBService1printListDBObj(mongoDBService1find(dbObject));        Systemoutprintln("——————————————————find sort——————————————————");        mongoDBService1printListDBObj(mongoDBService1find(new BasicDBObject(), new BasicDBObject("age", 1)));        Systemoutprintln("——————————————————find sort limit——————————————————");        mongoDBService1printListDBObj(mongoDBService1find(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");             mongoDBService1printListDBObj(mongoDBService1find(searchQuery));        Systemoutprintln("——————————————————update——————————————————");        mongoDBService1update(newDocument, searchQuery);        mongoDBService1printListDBObj(mongoDBService1find(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");        List<dbobject> list = new ArrayList<dbobject>();        listadd(dbObject1);        listadd(dbObject2);        listadd(dbObject3);        listadd(dbObject4);        mongoDBService1printListDBObj(mongoDBService1findAll());        Systemoutprintln("——————————————————delete list——————————————————");        mongoDBService1deleteBatch(list);        Systemoutprintln("——————————————————delete one——————————————————");        mongoDBService1delete(dbObject5);        //Systemoutprintln("——————————————————delete all——————————————————");        //mongoDBService1delete(new BasicDBObject());        mongoDBService1printListDBObj(mongoDBService1findAll());    }}</dbobject></dbobject></dbobject></dbobject>

测试结果:

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

MongoDBServiceImpljava

public class MongoDBServiceImpl implements MongoDBService {    private String dbName;    private String collName;    private DB db;         //有参构造方法,指定数据库名与集合名    public MongoDBServiceImpl(String dbName, String collName) {        thisdbName = dbName;        thiscollName = collName;        try {            db = getDb();        } catch (Throwable e) {            eprintStackTrace();        }    }    //无参构造方法,返回配置文件配置的数据库对象引用,如果配置文件中没有设置则返回默认数据库对象引用    public MongoDBServiceImpl() {        getDb();    }    /      获取数据库对象,3种情况(优先级从高到低):     1、构造方法指定2、配置文件指定3、默认数据库     (情况2、3在MongoDButil中设置)     /    public DB getDb() {        if (thisdb == null) {            if (thisdbName == null) {                thisdb = MongoDBUtilgetDB();            } else {                thisdb = MongoDBUtilgetDBByName(thisdbName);            }        }        return thisdb;    }         /      获取集合对象,3种情况(优先级从高到低):     1、构造方法指定2、配置文件指定3、默认数据库     (情况2、3在MongoDButil中设置)     /    public DBCollection getCollection() {        if(thiscollName != null){            return dbgetCollection(thiscollName);        }        else {            return MongoDBUtilgetDBCollection();        }    }     public DBObject map2Obj(Map<string, object=""> map) {        DBObject obj = new BasicDBObject();        if (mapcontainsKey("class") && mapget("class") instanceof Class)            mapremove("class");        objputAll(map);        return obj;    }    //插入数据    public void insert(DBObject obj) {        getCollection()insert(obj);    }    //插入多条数据    public void insertBatch(List<dbobject> list) {        if (list == null || listisEmpty()) {            return;        }        List<dbobject> listDB = new ArrayList<dbobject>();        for (int i = 0; i < listsize(); i++) {            listDBadd(listget(i));        }        getCollection()insert(listDB);    }    //删除数据    public void delete(DBObject obj) {        getCollection()remove(obj);    }    //删除多条数据    public void deleteBatch(List<dbobject> list) {        if (list == null || listisEmpty()) {            return;        }        for (int i = 0; i < listsize(); i++) {            getCollection()remove(listget(i));        }    }    //获取集合中的数据数量    public long getCollectionCount() {        return getCollection()getCount();    }    //查找符合条件的数据数量    public long getCount(DBObject obj) {        if (obj != null)            return getCollection()getCount(obj);        return getCollectionCount();    }    //查找符合条件的数据    public List<dbobject> find(DBObject obj) {        DBCursor cur = getCollection()find(obj);        return DBCursor2list(cur);    }         //查找符合条件的数据并排序    @Override    public List<dbobject> find(DBObject query, DBObject sort) {        DBCursor cur;        if (query != null) {            cur = getCollection()find(query);        } else {            cur = getCollection()find();        }        if (sort != null) {            cursort(sort);        }        return DBCursor2list(cur);    }     //查找符合条件的数据并排序,规定数据个数    @Override    public List<dbobject> 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) {            cursort(sort);        }        if (start == 0) {            curbatchSize(limit);        } else {            curskip(start)limit(limit);        }        return DBCursor2list(cur);    }         //将DBCursor转化为list<dbobject>    private List<dbobject> DBCursor2list(DBCursor cur) {        List<dbobject> list = new ArrayList<dbobject>();        if (cur != null) {            list = curtoArray();        }        return list;    }     //更新数据    public void update(DBObject setFields, DBObject whereFields) {        getCollection()updateMulti(whereFields, setFields);    }    //查询集合中所有数据    public List<dbobject> findAll() {        DBCursor cur = getCollection()find();        List<dbobject> list = new ArrayList<dbobject>();        if (cur != null) {            list = curtoArray();        }        return list;    }     //由ID获取数据    public DBObject getById(String id) {        DBObject obj = new BasicDBObject();        objput("_id", new ObjectId(id));        DBObject result = getCollection()findOne(obj);        return result;    }     public String getDbName() {        return dbName;    }     public void setDbName(String dbName) {        thisdbName = dbName;        thisdb = MongoDBUtilgetDBByName(thisdbName);    }     public String getCollName() {        return collName;    }     public void setCollName(String collName) {        thiscollName = collName;    }    @Override    public void printListDBObj(List<dbobject> list) {        // TODO Auto-generated method stub        for(DBObject dbObject: list){            Systemoutprintln(dbObject);        }    }       }</dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></string,>

MongoDBUtiljava

public class MongoDBUtil {    // 定义默认配置,1、IP地址 2、端口号 3、用户名 4、密码 5、配置文件位置名 6、数据库名    private static final String MONGODB_ADDRESS = "127001";    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 = "mongodbcfgproperties";    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 Map<string, string=""> cfgMap = new HashMap<string, string="">();    private static Hashtable<string, db=""> mongoDBs = new Hashtable<string, 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 = mongogetDB(dbName);        if (!mongoDBscontains(db)) {            Systemoutprintln("add");            dbaddUser(cfgMapget("mongodbusername"),                    cfgMapget("mongodbpassword")toCharArray());            mongoDBsput(dbName, db);        }        return db;    }     // ————————————————————————————————————初始化过程————————————————————————————————————    /      获取配置文件mongedbcfgproperties的文件对象     /    public static File getConfigFile() {        String path = MongoDBUtilclassgetResource("/")getPath();        String fileName = path + MONGODB_RESOURCE_FILE;        Systemoutprintln(fileName);        File file = new File(fileName);        if (fileexists()) {            return file;        }        return null;    }     /      通过mongedbcfgproperties配置文件初始化配置映射集合,如果没有编写配置文件,则加载程序指定的默认配置     /    @SuppressWarnings("unchecked")    private static void initCfgMap() {        File file = getConfigFile();        if (file != null) {            Properties p = new Properties();            try {                pload(new FileInputStream(file));                for (Enumeration enu = ppropertyNames(); enuhasMoreElements();) {                    String key = (String) enunextElement();                    String value = (String) pgetProperty(key);                    cfgMapput(key, value);                }            } catch (IOException e) {                Systemoutprintln("加载Mongo配置文件失败!");                eprintStackTrace();            }        } else { // 如果没有编写配置文件,则加载默认配置            cfgMapput("mongodbaddress", MONGODB_ADDRESS);            cfgMapput("mongodbport", StringvalueOf(MONGODB_PORT));            cfgMapput("mongodbusername", MONGODB_USERNAME);            cfgMapput("mongodbpassword", MONGODB_PASSWORD);            cfgMapput("mongodbdbname", MONGODB_DBNAME);            cfgMapput("mongodbcollectionname", MONGODB_COLLECTIONNAME);        }    }     /      初始化Mongo的数据库(将db指向相应对象引用,将collection指向相应对象引用,通过mongoDBs记录现有数据库对象)     /    @SuppressWarnings("deprecation")    private static void init() {        initCfgMap();        try {            String address = cfgMapget("mongodbaddress");            int port = IntegerparseInt(cfgMapget("mongodbport")toString());            String dbName = cfgMapget("mongodbdbname");            String username = cfgMapget("mongodbusername");            String password = cfgMapget("mongodbpassword");            String collectionName = cfgMapget("mongodbcollectionname");            mongo = new Mongo(address, port);            if (dbName != null && !""equals(dbName)) {                db = mongogetDB(dbName);                if (username != null && !""equals(username)) {                    dbaddUser(username, passwordtoCharArray());                    if (collectionName != null && !""equals(collectionName)) {                        collection = dbgetCollection(collectionName);                    }                }                mongoDBsput(dbName, db);            }        } catch (Exception e) {            eprintStackTrace();        }    } }

package basic;

import javasqlConnection;

import javasqlDriverManager;

import javasqlPreparedStatement;

import javasqlResultSet;

import javasqlSQLException;

import javasqlStatement;

public class JDBC {

public void findAll() {

try {

// 获得数据库驱动

//由于长时间不写,驱动名和URL都忘记了,不知道对不对,你应该知道的,自己改一下的哈

String url = "jdbc:oracle:thin:@localhost:1521:XE";

String userName = "system";

String password = "system";

ClassforName("oraclejdbcdriverOracleDriver");

// 创建连接

Connection conn = DriverManagergetConnection(url, userName,

password);

// 新建发送sql语句的对象

Statement st = conncreateStatement();

// 执行sql

String sql = "select from users";

ResultSet rs = stexecuteQuery(sql);

// 处理结果

while(rsnext()){

//这个地方就是给你的封装类属性赋值

Systemoutprintln("UserName:"+rsgetString(0));

}

// 关闭连接

rsclose();

stclose();

connclose();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

eprintStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

public void delete(){

try {

//步骤还是那六个步骤,前边的两步是一样的

String url = "jdbc:oracle:thin:@localhost:1521:XE";

String userName = "system";

String password = "system";

ClassforName("oraclejdbcdriverOracleDriver");

Connection conn = DriverManagergetConnection(url,userName,password);

//这里的发送sql语句的对象是PreparedStatement,成为预处理sql对象,因为按条件删除是需要不定值的

String sql = "delete from users where id = ";

PreparedStatement ps = connprepareStatement(sql);

pssetInt(0, 1);

int row = psexecuteUpdate();

if(row!=0){

Systemoutprintln("删除成功!");

}

// 关闭连接

rsclose();

stclose();

connclose();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

eprintStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

}

我只写了查询和删除,添加、修改和删除非常之像,这是因为查询对数据库没有改动,而增删改都对数据库进行了修改,所以这三个非常像……呵呵,你自己看着办吧

jsp中的增删改查是通过 *** 作特定条件来实现动态改变Map的值来实现的。

比如根据部门id来查询:

定义一个存放部门信息的map,如下:

Map<integer,Dept> map=new HashMap<integer,Dept>();

查询方法:

Iterator keys = mapkeySet()iterator();

while(keyshasNext()){

String key = (String)keysnext();

if("id"equals(key)){

Systemoutprintln("id为xx的员工信息");

}

}

添加是这样的mapput("001",new Dept());

删除是这样的mapremove();

更新是直接用mapput(key,value),这个方法会覆盖原来这个key对应的值,就相当于更新了

以上就是关于java在access数据库下实现增删改查全部的内容,包括:java在access数据库下实现增删改查、请问如何对用Java对mysql进行增删改查等方法、java对所有mongodb表进行增删改查表名怎么设置等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

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

原文地址: http://outofmemory.cn/sjk/9347022.html

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

发表评论

登录后才能评论

评论列表(0条)

保存