首页数据库java数据库增删改查?急用java写一个 连接数据库 增删改的例子

java数据库增删改查?急用java写一个 连接数据库 增删改的例子

编程之家2023-10-2193次浏览

其实java数据库增删改查的问题并不复杂,但是又很多的朋友都不太了解急用java写一个 连接数据库 增删改的例子,因此呢,今天小编就来为大家分享java数据库增删改查的一些知识,希望可以帮助到大家,下面我们一起来看看这个问题的分析吧!

java数据库增删改查?急用java写一个 连接数据库 增删改的例子

(JAVA)怎样将对数据库的增删查改方法封装起来便于以后调用

public class DBRecordSet{

static private Logger log= Logger.getLogger(DBRecordSet.class.getName());

ResultSetMetaData md= null;

Connection conInner= null;

private int firstElementOfThisList= 0;//当前缓冲池中保存的记录在整个结果集中的位置

private int countOfElementsInthisList= 0;//缓冲池中记录的数目

java数据库增删改查?急用java写一个 连接数据库 增删改的例子

private List resultList= null;//保存结果的缓冲池

private Vector columnMap= null;

private int cacheSize=-1;//保存结果的缓冲池大小

private int maxRecords= 10;//执行结果集的时候得到的最多的记录数

private String strSQLStmt= null;//打开结果集的时候执行的SQL语句

private boolean isClosed= true;//结果集是否已经open

java数据库增删改查?急用java写一个 连接数据库 增删改的例子

private int columnCount=-1;//结果集字段数目

private int columnTypeInt[]= null;

private String columnTypeString[]= null;

private int curRow= 0;//当前光标所在行,基数为 1

private int maxRow=-1;//执行查询语句得到的记录数,基数为 1

private int curPage=-1;//分页显示时当前所在页,基数为 1

private int pageSize=-1;//分页显示时每页记录数,基数为 1

private int pageCount=-1;//分页显示时总页数,基数为 1

private int updateCount=-1;

private boolean cursorDir= true;

DBConnectionManager connMgr= null;

private DBConnectionManager getConnectionManager(){

if(connMgr== null){

connMgr= DBConnectionManager.getInstance();

}

return connMgr;

}

private int getCacheSize(){

if(this.cacheSize==-1){

cacheSize= getConnectionManager().getCacheSize();

if(cacheSize<= 0)

cacheSize= 50;

}

return this.cacheSize;

}

public void setCacheSize(int size){

this.cacheSize= size;

}

/**

*构造函数

*/

public DBRecordSet(){

close();

}

public int execute(Connection con, String sql){

if(con== null|| sql== null|| sql.length()<= 0){

return-1;

}

Statement stmt= null;

try{

if(con.isClosed()) return-1;

stmt= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

//设置 ResultSet对象可包含的最多行数

if(maxRecords> 1) stmt.setMaxRows(maxRecords);

//执行语句,判断语句类型

log.debug("开始执行SQL语句:"+ sql);

int resultCount= stmt.executeUpdate(sql);

log.debug("执行SQL语句成功:"+ sql+";返回结果数目为"+ resultCount);

return resultCount;

} catch(Exception e){

log.error("执行SQL语句失败:"+ e.getMessage());

} finally{

try{

if(stmt!= null)

stmt.close();

} catch(Exception e){

log.error("关闭Statement失败:"+ e.getMessage());

return-1;

}

}

return-1;

}

public boolean openSelect(Connection con, String sql){

Statement stmt= null;

ResultSet rs= null;

int n= 0, i= 0;

if(con== null) return false;

firstElementOfThisList= 0;

countOfElementsInthisList= 0;

try{

if(con.isClosed()) return false;

stmt= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

//设置 ResultSet对象可包含的最多行数

if(maxRecords> 1) stmt.setMaxRows(maxRecords);

//执行语句,判断语句类型

log.debug("开始执行SQL语句:"+ sql);

if(stmt.execute(sql)){

log.debug("执行查询语句成功");

rs= stmt.getResultSet();

md= rs.getMetaData();

columnCount= md.getColumnCount();

updateCount=-1;

if(resultList!= null){

resultList.clear();

resultList= null;

}

resultList= new ArrayList();

if(columnMap!= null){

columnMap= null;

}

columnMap= new Vector(columnCount);

for(n= 1; n<= columnCount;++n){

String columnName= md.getColumnName(n).trim();

columnName= columnName.toLowerCase();

if(columnName== null|| columnName.length()<= 0){

columnName="vcolumn_"+ String.valueOf(n);

}

if(columnMap.contains(columnName)){

columnName+="_"+ String.valueOf(n);

}

columnMap.add(columnName);

}

/*

for(n= 1; n<= columnCount;++n){

log.debug("查询语句结果集的列"+ n+":"+ String.valueOf(columnMap.get(n- 1)));

}

*/

PropertyContainer property= null;

while(rs.next()&& i< getCacheSize()){

property= new PropertyContainerImpl();

for(n= 1; n<= columnCount;++n){

try{

property.addPropertyBy(String.valueOf(columnMap.get(n- 1)), rs.getObject(n));

} catch(Exception e){

property.addPropertyBy(String.valueOf(columnMap.get(n- 1)), rs.getString(n));

}

}

resultList.add(property);

i++;

}

if(property!= null)

log.debug("Open查询的最后一条记录是:"+ property.valueToString());

if(i> 0){//如果有记录取出

firstElementOfThisList= 1;

countOfElementsInthisList= resultList.size();

maxRow= i;

if(i>= getCacheSize()){//记录没有取完

//注意:为了兼容以前代码,这里需要将结果集滚动到最后,用来获得记录数目

while(rs.next()) maxRow++;

maxRow++;

}

curRow= 0;

} else{//如果没有记录

firstElementOfThisList= 0;

countOfElementsInthisList= 0;

curRow=-1;

maxRow= 0;

log.debug("没有记录返回:"+ sql);

}

log.debug("open:读取从第0条记录开始的"+ getCacheSize()+"条记录,返回记录"+ countOfElementsInthisList+"条。总记录数为"+ maxRow+"条");

} else{

//执行更新语句后将查询结果集关闭并清除各项信息

int updatecount= stmt.getUpdateCount();

close();

updateCount= updatecount;

log.debug("成功执行更新语句");

}//保存执行的SQL语句

strSQLStmt= sql;

} catch(SQLException e){

log.error(e.toString()+":执行SQL语句时出错:"+ sql);

return false;

} catch(Exception e){

log.error(e.toString()+":执行SQL语句时出错:"+ sql);

return false;

} finally{

try{

if(rs!= null){

rs.close();

rs= null;

}

if(stmt!= null){

stmt.close();

stmt= null;

}

//getConnectionManager().freeConnectionInner(con);

} catch(Exception e){

log.error(e.toString()+":结果集不能正确关闭");

//getConnectionManager().freeConnectionInner(con);

return false;

}

}

isClosed= false;

return true;

}

/**

*执行SQL语句,可以为查询或更新语句。

*执行更新语句后调用 getUpdateCount()取得所更新的记录数

*

*@param sql执行的SQL语句

*/

public boolean open(String sql){

Statement stmt= null;

ResultSet rs= null;

int n= 0, i= 0;

Connection con= getConnectionManager().getConnectionInner();

if(con== null) return false;

firstElementOfThisList= 0;

countOfElementsInthisList= 0;

try{

if(con.isClosed()) return false;

stmt= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

//设置 ResultSet对象可包含的最多行数

if(maxRecords> 1) stmt.setMaxRows(maxRecords);

//执行语句,判断语句类型

log.debug("开始执行SQL语句:"+ sql);

if(stmt.execute(sql)){

log.debug("执行查询语句成功");

rs= stmt.getResultSet();

md= rs.getMetaData();

columnCount= md.getColumnCount();

updateCount=-1;

if(resultList!= null){

resultList.clear();

resultList= null;

}

resultList= new ArrayList();

if(columnMap!= null){

columnMap= null;

}

columnMap= new Vector(columnCount);

for(n= 1; n<= columnCount;++n){

String columnName= md.getColumnName(n).trim();

columnName= columnName.toLowerCase();

if(columnName== null|| columnName.length()<= 0){

columnName="vcolumn_"+ String.valueOf(n);

}

if(columnMap.contains(columnName)){

columnName+="_"+ String.valueOf(n);

}

columnMap.add(columnName);

}

/*

for(n= 1; n<= columnCount;++n){

log.debug("查询语句结果集的列"+ n+":"+ String.valueOf(columnMap.get(n- 1)));

}

*/

PropertyContainer property= null;

while(rs.next()&& i< getCacheSize()){

property= new PropertyContainerImpl();

for(n= 1; n<= columnCount;++n){

try{

property.addPropertyBy(String.valueOf(columnMap.get(n- 1)), rs.getObject(n));

} catch(Exception e){

property.addPropertyBy(String.valueOf(columnMap.get(n- 1)), rs.getString(n));

}

}

resultList.add(property);

i++;

}

if(property!= null)

log.debug("Open查询的最后一条记录是:"+ property.valueToString());

if(i> 0){//如果有记录取出

firstElementOfThisList= 1;

countOfElementsInthisList= resultList.size();

maxRow= i;

if(i>= getCacheSize()){//记录没有取完

//注意:为了兼容以前代码,这里需要将结果集滚动到最后,用来获得记录数目

while(rs.next()) maxRow++;

maxRow++;

}

curRow= 0;

} else{//如果没有记录

firstElementOfThisList= 0;

countOfElementsInthisList= 0;

curRow=-1;

maxRow= 0;

log.debug("没有记录返回:"+ sql);

}

log.debug("open:读取从第0条记录开始的"+ getCacheSize()+"条记录,返回记录"+ countOfElementsInthisList+"条。总记录数为"+ maxRow+"条");

} else{

//执行更新语句后将查询结果集关闭并清除各项信息

int updatecount= stmt.getUpdateCount();

close();

updateCount= updatecount;

log.debug("成功执行更新语句");

}//保存执行的SQL语句

strSQLStmt= sql;

} catch(SQLException e){

log.error(e.toString()+":执行SQL语句时出错:"+ sql);

return false;

} catch(Exception e){

log.error(e.toString()+":执行SQL语句时出错:"+ sql);

return false;

} finally{

try{

if(rs!= null){

rs.close();

rs= null;

}

if(stmt!= null){

stmt.close();

stmt= null;

}

getConnectionManager().freeConnectionInner(con);

} catch(Exception e){

log.error(e.toString()+":结果集不能正确关闭");

getConnectionManager().freeConnectionInner(con);

return false;

}

}

isClosed= false;

return true;

}

/**

*根据语句,得到从startIndex开始的count条记录

*/

private void getResultAt(int start, int count) throws Exception{

if(isClosed){

throw new Exception("还没有打开结果集");

}

Statement stmt= null;

ResultSet rs= null;

Connection con= getConnectionManager().getConnectionInner();

int readStart= start;

int readCount= count;

if(con== null){

log.error("无法获得有效连接");

throw new Exception("getResultAt:无法获得有效连接");

}

try{

stmt= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

rs= stmt.executeQuery(strSQLStmt);

if(resultList!= null){

resultList.clear();

resultList= null;

}

resultList= new ArrayList();

// skip initial rows as specified by the start parameter.

while(start--> 1&& rs.next());

//分别对每一个字段,取出数值,放到BaseBusinessObject的PropertyContainer中

while(count--> 0&& rs.next()){

PropertyContainer property= new PropertyContainerImpl();

for(int n= 1; n<= columnCount;++n){

try{

property.addPropertyBy(String.valueOf(columnMap.get(n- 1)), rs.getObject(n));

} catch(Exception e){

property.addPropertyBy(String.valueOf(columnMap.get(n- 1)), rs.getString(n));

}

}

resultList.add(property);

}

log.debug("getResultAt:读取从第"+ readStart+"条记录开始的"+ readCount+"条记录,返回记录"+ resultList.size()+"条");

} catch(SQLException e){

throw new Exception(e.toString());

} finally{

try{

if(rs!= null){

rs.close();

rs= null;

}

if(stmt!= null){

stmt.close();

stmt= null;

}

getConnectionManager().freeConnectionInner(con);

} catch(Exception e){

log.error(e.toString()+":结果集不能正确关闭");

getConnectionManager().freeConnectionInner(con);

}

}

}

/**

*执行SQL语句,可以为查询或更新语句。

*执行更新语句后调用 getUpdateCount()取得所更新的记录数

*

*@param sql执行的SQL语句

*/

public boolean openGBK(String sql){

return open(Convert.toGBK(sql));

}

/**

*返回执行查询语句后表的列数

*/

public int getColumnCount(){

return columnCount;

}

/**

*返回每列的类型,基数为 1

*

*@param schema表模式名

*@param table表名

*/

public int[] getColumnType(String schema, String table){

Connection con= null;

ResultSet results= null;

List list= new ArrayList();

if(columnTypeInt== null){

log.debug("getColumnType: getConnection");

con= getConnectionManager().getConnectionInner();

if(con== null) return null;

try{

DatabaseMetaData dmd;

dmd= con.getMetaData();

results= dmd.getColumns(null, null, table.toUpperCase(), null);

//

while(results.next()){

list.add(new Integer(results.getInt("DATA_TYPE")));

}

columnTypeInt= new int[list.size()];

for(int i= 0; i< list.size(); i++){

Integer type=(Integer)list.get(i);

columnTypeInt[i]= type.intValue();

}

} catch(Exception e){

return null;

} finally{

try{

results.close();

getConnectionManager().freeConnectionInner(con);

} catch(Exception e){

getConnectionManager().freeConnectionInner(con);

log.error(e.toString()+":结果集不能正确关闭");

return null;

}

}

}

return columnTypeInt;

}

/**

*返回每列的名称,基数为 1

*

*@param schema表模式名

*@param table表名

*/

public String[] getColumnName(String schema, String table){

Connection con= null;

ResultSet results= null;

if(columnTypeString== null){

log.debug("getColumnName: getConnection");

con= getConnectionManager().getConnectionInner();

if(con== null) return null;

try{

DatabaseMetaData dmd;

dmd= con.getMetaData();

results= dmd.getColumns(null, null, table.toUpperCase(), null);

//

int i= 1;

while(results.next()) i++;

columnTypeString= new String[i];

i= 1;

results.beforeFirst();

while(results.next()) columnTypeString[i++]= results.getString("COLUMN_NAME").trim();

} catch(Exception e){

return null;

} finally{

try{

results.close();

getConnectionManager().freeConnectionInner(con);

} catch(Exception e){

getConnectionManager().freeConnectionInner(con);

log.error(e.toString()+":结果集不能正确关闭");

return null;

}

}

}

return columnTypeString;

}

/**

*返回执行更新语句后实际更新的记录数

*/

public int getUpdateCount(){

return updateCount;

}

/**

*设置查询语句执行完后取得的最大记录数

*

*@param maxrec最大记录数

*/

public void setMaxRecords(int maxrec){

maxRecords= maxrec;

}

/**

*返回查询语句执行完后取得的最大记录数

*/

public int getMaxRecords(){

return maxRecords;

}

/**

*关闭查询结果集并清除各项信息

*/

public void close(){

md= null;

firstElementOfThisList= 0;//当前缓冲池中保存的记录在整个结果集中的位置

countOfElementsInthisList= 0;//缓冲池中记录的数目

if(resultList!= null){

int size= resultList.size();

急用java写一个 连接数据库 增删改的例子

DBConnectionManager.java//连接数据库用的

import java.sql.*;

public class DBConnectionManager{

private String driverName="com.microsoft.jdbc.sqlserver.SQLServerDriver";

private String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=demo";

private String user="sa";

private String password="";

public String getDriverName(){

return driverName;

}

public void setDriverName(String driverName){

this.driverName= driverName;

}

public String getPassword(){

return password;

}

public void setPassword(String password){

this.password= password;

}

public String getUrl(){

return url;

}

public void setUrl(String url){

this.url= url;

}

public String getUser(){

return user;

}

public void setUser(String user){

this.user= user;

}

public Connection getConnection(){

try{

Class.forName(driverName);

return DriverManager.getConnection(url, user, password);

}catch(Exception e){

e.printStackTrace();

return null;

}

}

}

DBSQLManager.java//操作数据库用的

import java.sql.*;

public class DBSQLManager{

protected Connection con=null;//Connection对象

protected Statement stmt=null;//Statement对象

protected ResultSet rs=null;//记录结果集

protected String sql="";//SQL语句

public DBSQLManager(){

try{

DBConnectionManager dcm=new DBConnectionManager();

con=dcm.getConnection();

//con.setAutoCommit(false);//添加事物,既是否自动提交

stmt=con.createStatement();

} catch(SQLException e){

e.printStackTrace();

}

}

public Statement getStmt(){

return stmt;

}

public Connection getCon(){

return con;

}

public ResultSet getRs(){

return rs;

}

public void setSql(String sql){

this.sql=sql;

}

public String getSql(){

return sql;

}

//查找

public void execueQuery(){

try{

rs=stmt.executeQuery(sql);

} catch(SQLException e){

e.printStackTrace();

}

}

//更新

public void executeUpdate(){

try{

stmt.executeUpdate(sql);

} catch(SQLException e){

e.printStackTrace();

}

}

//关闭

public void close(){

if(rs!=null){

try{

rs.close();

} catch(SQLException e){

e.printStackTrace();

}

rs=null;

}

if(stmt!=null){

try{

stmt.close();

} catch(SQLException e){

e.printStackTrace();

}

stmt=null;

}

try{

con.close();

} catch(SQLException e){

e.printStackTrace();

}

con=null;

}

}

SqlOperate.java//用来调用数据库操作语句

import java.sql.ResultSet;

import java.sql.SQLException;

public class SqlOperate{

//插入,修改,删除

public void insOrModOrDel(String sql){

DBSQLManager dbsm=new DBSQLManager();

dbsm.getStmt();

dbsm.setSql(sql);

dbsm.executeUpdate();

dbsm.close();

}

//显示

public void display(String sql){

DBSQLManager dbsm=new DBSQLManager();

dbsm.getStmt();

dbsm.setSql(sql);

dbsm.execueQuery();

ResultSet rs=dbsm.getRs();

try{

while(rs!=null&&rs.next()){

System.out.print(rs.getObject(1)+"\t");

System.out.print(rs.getObject(2)+"\t");

System.out.print(rs.getObject(3)+"\t");

System.out.println(rs.getObject(4));

}

dbsm.close();

} catch(SQLException e){

e.printStackTrace();

}

}

}

SqlMain.java//数据库的测试主函数

public class SqlMain{

public static void main(String[] args){

SqlOperate sqlOpt=new SqlOperate();

// sqlOpt.insOrModOrDel("insert into user1 values('qianhaifei',999999,'qianhaifei@163.com')");//插入

// sqlOpt.insOrModOrDel("update user1 set username='weixiangyang' where id=4");//修改

// sqlOpt.insOrModOrDel("delete from user1 where username='weixy2000'");//删除

sqlOpt.display("select*from user1");//显示

}

}

楼主用的时间只需要将数据库用户名和密码还有数据库表名改一下就行了...

其他都是一样的...

楼主会改吧.../???

如果有什么问题的话请百度HI我...帮你解决....

如果楼主要我的数据库的话....请百度HI我...我给你就行了...

祝楼主早日成功!

如何使用java对oracle数据库进行增删查改

用eclipse

首先在oracle文件下找到jdbc文件,里面的lib文件下有个class12.zip

在eclipse里新建个项目,建好后在左边右击那个项目图标,选择属性(最下面的),里面有个java build path,点进去,找到add external jars按键,点一下,把那个class12.zip加载进来,然后可以开始写代码了。

我的代码如下:

import java.sql.*;

public class connect{

/**

*@param args

*/

public static void main(String[] args){

// TODO Auto-generated method stub

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

}catch(ClassNotFoundException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

Connection con= null;

Statement stmt= null;

ResultSet rs= null;

try{

String url="jdbc:oracle:thin:@服务器ip地址:端口号:数据库名字";

String user="用户名";

String password="密码";

String str="INSERT INTO ZZZ_2 VALUES('041110018','JHDK')";

con= java.sql.DriverManager.getConnection(url,user,password);

//创建状态

stmt= con.createStatement();

//执行SQL语句,返回结果集

//int rowcount= stmt.executeUpdate(str);

int j= stmt.executeUpdate("update ZZZ_2 set NAME='dbt' where ID=21");

int k= stmt.executeUpdate("delete from ZZZ_2 where ID=41110020");

rs= stmt.executeQuery("SELECT* FROM ZZZ_2");

//对结果集进行处理

while(rs.next()){

int id= rs.getInt("ID");

String name= rs.getString("NAME");

//Integer age= rs.getObject("age")== null? null: rs.getInt("age");

System.out.println(id+":"+ name);

}}catch(SQLException e){

e.printStackTrace();}

//释放资源

finally{

try{

rs.close();

}catch(SQLException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

try{

stmt.close();

}catch(SQLException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

try{

con.close();

}catch(SQLException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

注意,上面的ip地址什么的要填对,ZZZ_2是我随便建的表,你改成自己的表名就行了

如果你还想了解更多这方面的信息,记得收藏关注本站。

小型数据库有哪些,小数据库有哪些ora01109数据库未打开 oracle数据库恢复,提示ORA-01110: 数据文件 35: &#39;&#39;