导出数据库数据的方法,适合简单的数据库表格结构

1  如果是导出数据库,可以用java调用数据库的备份SQl语句
2  如果仅仅导出数据,请参考如下样例,其中tablename是表格的名字,pk指是否包含主键
注意:对于二进制和包含特殊字符的字段数据,需要额外处理,目前这个只能用于最简单的。
另:可参考 phpMyAdmin的导出功能
本代码采用SQL Server 
2000  数据库

[code
= Java]
<% @ page language = " java "  contentType = " text/html; charset=GBK "  pageEncoding = " GBK " %>
<% @ page  import = " java.sql.* " %>
<%
  
boolean  showPK  =  ParamUtils.getIntParameter(request,  " pk " 0 ==   1 ;
  String tableName 
=  request.getParameter( " tablename " );
  
if  (tableName  ==   null   ||  tableName.trim().length()  ==   0 {
    out.println(
"表格名称为空!");
    
return;
  }


  Connection con 
=   null ;
  Statement stat 
=   null ;
  ResultSet rs 
=   null ;
  
try   {

    con 
= Factory.getDataSource().getConnection();
    
if (con == null{
      out.println(
"得到数据库连接失败!");
      
return;
    }

    stat 
= con.createStatement();
    rs 
= stat.executeQuery("select * from " + tableName + " " + NoNull.toString(request.getParameter("sql")));

    
if(showPK){
      out.print(
"SET IDENTITY_INSERT dbo."+tableName+" ON<br>");
    }

    
    ResultSetMetaData md 
= rs.getMetaData();
    String[] fieldNames 
= new String[md.getColumnCount()];
    StringBuilder builder 
= new StringBuilder("insert into " + tableName + "(");
    
for (int i = 0; i < md.getColumnCount(); i++{
      fieldNames[i] 
= md.getColumnName(i + 1);
      
if (!showPK && fieldNames[i].equalsIgnoreCase("ID")) {
    
continue;
      }

      builder.append(fieldNames[i] 
+ ",");
    }

    
// 去掉最后一个逗号
    builder.deleteCharAt(builder.length() - 1);
    builder.append(
") values(");
    StringBuilder line 
= new StringBuilder();
    String value;
    
while (rs.next()) {
      line.delete(
0, line.length());
      line.append(builder.toString());
      
for (int i = 0; i < fieldNames.length; i++{
    
if (!showPK && fieldNames[i].equalsIgnoreCase("ID")) {
      
continue;
    }

    value 
= rs.getString(fieldNames[i]);
    
if (value == null{
      line.append(
"null,");
    }
 else {
      line.append(
"'");
      line.append(value);
      line.append(
"',");
    }

      }

      line.deleteCharAt(line.length() 
- 1);
      line.append(
");");
      out.println(line.toString() 
+ "<br/>");
    }

    
if(showPK){
      out.print(
"SET IDENTITY_INSERT dbo."+tableName+" OFF<br>");
    }

  }
  catch  (Exception ex)  {
    out.print(ex);
  }
  finally   {
    
if (stat != null{
      
try {
    stat.close();
      }
 catch (Exception ex) {
      }

    }

    
if (con != null{
      
try {
    con.close();
      }
 catch (Exception ex) {
      }

    }

  }

%>
[
/ code]
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值