使用配置文件properties进行连接数据库

首先创建一个file自定义文件名,但是后缀名必须改为.properties(不分大小写):如config.properties;

然后双击config.properties进行编辑:此文件数据是根据键值对来存储的:我们可以把连接数据库的一些连接字符串存储在此文件里;然后用的时候直接读配置文件,到时候更换的时候方便移植和修改。

name                                                                               value

driver                                                                               com.microsoft.sqlserver.jdbc.SQLServerDriver

con                                                                                  jdbc\:sqlserver\://localhost\:1433;databaseName\=Test

user                                                                                 sa

pwd

然后用的时候:

public class TestMain {
     Connection con=null;
     Properties pro=new Properties();
     public TestMain() throws IOException, ClassNotFoundException, SQLException
     {
      pro.load(TestMain.class.getClassLoader().getResourceAsStream("config.properties"));
      //加载驱动
      Class.forName(pro.getProperty("driver"));
      //创建连接
      con=DriverManager.getConnection(pro.getProperty("con"),pro.getProperty("user"),pro.getProperty("pwd"));
     
     }

  //测试上传图片

   @Test
    public void setImg() throws SQLException, FileNotFoundException{
     String sql="INSERT INTO [Test].[dbo].[User]([name],[age],[image])VALUES(?,?,?)";
     PreparedStatement ps=con.prepareStatement(sql);
     ps.setObject(1,"测试name");
     ps.setObject(2,22);
     FileInputStream fis=new FileInputStream(new File("D:\\img\\Picture1.jpg"));//从D盘Img读取
     ps.setBinaryStream(3,fis);
     int num=ps.executeUpdate();
     System.out.println("num为:"+num);  
    }

    //取图片并写入到硬盘文件夹
    @Test
    public void getIma() throws SQLException, IOException{
      Statement state=con.createStatement();
     String sql="select [image] from [User] where id=6";
     ResultSet rs=state.executeQuery(sql);
     rs.next();
     InputStream input=rs.getBinaryStream(1);
     OutputStream out=new FileOutputStream("D:\\15.jpg");//写入到D盘
     byte[] bte=new byte[1024];
     int length=0;
     while((length=input.read(bte))>0){
      out.write(bte,0,length);
     }
     input.close();
     out.close();
    }

//批处理:测试时,使用批处理比使用循环.executeUpdate()节省大概一半时间
    @Test
    public void useBatch() throws SQLException{
     String sql="INSERT INTO [Test].[dbo].[User]([name],[age])VALUES(?,?)";
     PreparedStatement ps=con.prepareStatement(sql);
     long noe=System.currentTimeMillis();
     for (int j = 0; j < 10000; j++) {
      ps.setObject(1,"sp"+j);
         ps.setObject(2,j);
         //ps.executeUpdate();原时间为5875毫秒
         ps.addBatch();
         
  }
     ps.executeBatch();
     
     System.out.println("增加10000次的时间为:"+(System.currentTimeMillis()-noe));  
    }

 //时间戳
    @Test
    public void testDate() throws SQLException{
     String sql="INSERT INTO [Test].[dbo].[User]([name],[age],[startTime],[endTime])VALUES(?,?,?,?)";
     PreparedStatement ps=con.prepareStatement(sql);
     ps.setString(1,"测试名");
     ps.setInt(2,20);
     ps.setTimestamp(3,new Timestamp(System.currentTimeMillis()));
     ps.setDate(4,new Date(System.currentTimeMillis()));//这个Date是.sql包下的,不是.util包下的,莫导错包了!
     int zong=ps.executeUpdate();
     System.out.println("时间戳"+zong);   

}

    //测试回滚不提交
    @Test
    public void testTransaction() throws SQLException{
        con.setAutoCommit(false);//设置默认不自动提交
        try {
         String sql="update [User] set money=money-100 where id=5";
         Statement state=con.createStatement();
         state.executeUpdate(sql);
         //int a=10/0;
         sql="update [User] set money=money+100 where id=1";
         state.executeUpdate(sql);
         con.commit();//提交事务
  } catch (Exception e) {
   con.rollback();
  }
    //用jdbc同样可以实现事物回滚!如果没有设置默认不自动提交,那么执行到int a=10/0;就不向下执行了,转账会出现扣钱,没加钱的错误!
    }

}

还有,这里在执行读取操作的时候,用到了 rs.getMetaData().getColumnCount();和rs.getMetaData().getColumnName()很有用;

 private List<Map<String,Object>> setMap() throws SQLException{
      List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
      Statement state=con.createStatement();
      
      String sql="select * from [User]";
   ResultSet rs=state.executeQuery(sql);
   while(rs.next()){
    Map<String,Object> map=new HashMap<String, Object>();
    for (int i = 1; i <=rs.getMetaData().getColumnCount(); i++) {
    map.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
    }
          list.add(map);
   }  
      rs.close();
      state.close();
      con.close();
   return list;
     }
     @Test
     public void getMap() throws SQLException{
      List<User> users=new ArrayList<User>();
      List<Map<String,Object>> list=setMap();
      for (Map<String, Object> map : list) {
       User user=new User();
    user.setAge(Integer.valueOf((map.get("age").toString())));
    user.setId(Integer.valueOf((map.get("id").toString())));
    user.setName(map.get("name").toString());
    users.add(user);
  }
     
      for (User item : users) {
   p(item.getId()+"\t"+item.getAge()+"\t"+item.getName());
  }
     }
    
    
    
    
     @Test
     public void getList() throws SQLException{
      List<List> list=setList();
      for (List list2 : list) {
   for (Object object : list2) {
    p(object);
   }
  }
     }
    private List<List> setList() throws SQLException{
     Statement state=con.createStatement();
     List<List> list=new ArrayList<List>();
     String sql="select * from [User]";
  ResultSet rs=state.executeQuery(sql);
  while(rs.next()){
   List l=new ArrayList();
   for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
   l.add(rs.getObject(i));
   }
         list.add(l);
  }  
     rs.close();
     state.close();
     con.close();
  return list;
     
    }

 

复习课程jdbc:使用配置文件properties进行连接数据库,数据库存取图片,批处理,时间戳,事物回滚等等的更多相关文章

  1. java jdbc使用配置文件连接数据库:

    java jdbc使用配置文件连接数据库: 创建后缀名为:.properties的文件,文件内容包括,数据库驱动.连接的数据库地址.用户名.密码…… 以Mysql为例创建config.properti ...

  2. JDBC实例--通过连接工具类DBUtil +配置文件来获取连接数据库,方便又快捷

    根据前面的连接方法,还有缺点就是,如果人家要换数据库,还得改动源代码,然后还要编译什么的.这样客户修改也不容易. 做法:我们写一个配置文件,把该数据写在配置文件上面,然后通过类来加载改文件,然后读取相 ...

  3. 读取配置文件properties的几种方式

    介绍几种读取方式:参考:https://www.cnblogs.com/sebastian-tyd/p/7895182.html .基于ClassLoder读取配置文件 注意:该方式只能读取类路径下的 ...

  4. MyBatis XML 配置文件 properties 元素扩展

    在分析 MyBatis XML 配置文件 properties 元素时提到了三种配置方式,其中 property 子元素 和 properties 文件都比较容易理解,但是为什么还要提供一种代码参数传 ...

  5. 操作配置文件Properties

    // */ // ]]>   操作配置文件Properties Table of Contents 1 定义 2 读取配置值 3 修改和保存配置 4 注意 1 定义 csharp中在Settin ...

  6. Java配置文件Properties的读取、写入与更新操作

    /** * 实现对Java配置文件Properties的读取.写入与更新操作 */ package test; import java.io.BufferedInputStream; import j ...

  7. 【转】spring管理属性配置文件properties——使用PropertiesFactoryBean|spring管理属性配置文件properties——使用PropertyPlaceholderConfigurer

     spring管理属性配置文件properties--使用PropertiesFactoryBean 对于属性配置,一般采用的是键值对的形式,如:key=value属性配置文件一般使用的是XXX.pr ...

  8. 对Java配置文件Properties的读取、写入与更新操作

    http://breezylee.iteye.com/blog/1340868 对Java配置文件Properties的读取.写入与更新操作 博客分类: javase properties  对Jav ...

  9. 实现对Java配置文件Properties的读取、写入与更新操作

    /** * 实现对Java配置文件Properties的读取.写入与更新操作 */ package test; import java.io.BufferedInputStream; import j ...

随机推荐

  1. Day09

    Servlet概述 生命周期方法: void init(ServletConfig):出生之后(1次): void service(ServletRequest request, ServletRes ...

  2. IE 的resize事件问题

    window的resize事件,真的让人无语! 我在动态设置元素的HTML内容后,窗口高度变化了,可是却不触发resize事件. 但是我在访问document.documentElement.scro ...

  3. 低功耗蓝牙4.0BLE编程-nrf51822开发(8)-GATT

    The Generic Attribute Profile (GATT)使用属性定义一个服务框架,定义了服务和特性的过程和数据格式,包含发现.读取.写入.通知指示特性和配置特性广播. GATT配置文件 ...

  4. linux shell send and receive emails

    http://www.netcan666.com/2016/02/20/%E5%88%A9%E7%94%A8telnet%E5%9C%A8%E5%91%BD%E4%BB%A4%E8%A1%8C%E5% ...

  5. 常用jQuery代码02

    一.each函数拿到每个元素的宽度 setTimeout(function () { $(".sticker_list img").each(function () { var W ...

  6. Magento Error – The directory is not writable by server.

    When trying to use the insert image functionality in Magento if you receive an error saying: “The di ...

  7. [LeetCode]题解(python):032-Longest Valid Parentheses

    题目来源 https://leetcode.com/problems/longest-valid-parentheses/ Given a string containing just the cha ...

  8. GIS 学习及参考站点

    地理信息论坛 GIS空间站 GISALL 广东水利厅 flex版的

  9. web调试工具-firebug

    Firebug是网页浏览器firefox下面的一款开发类插件.它集HTML查看和编辑,js控制台,网络状况监视器于一体,是开发js,css,HTML:和Ajax的得力助手 (自己整理的,有错误的话见谅 ...

  10. iOS:runtime最全的知识总结

    runtime 完整总结 好东西,应该拿出来与大家分享... 南峰子博客地址:http://southpeak.github.io/blog/categories/ios/ 原文链接:http://w ...