好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JDBC_04_使用Properties集合保存JDBC所需配置信息

使用Properties集合保存JDBC所需配置信息

将JDBC连接所需的配置信息保存在一个配置文件中,然后使用Properties将该信息存储起来,动态的完成JDBC的配置连接

代码:

 
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.IOException;
   import java.sql.Connection;
   import java.sql.DriverManager;
   import java.sql.SQLException;
   import java.sql.Statement;
   import java.util.Properties;


   public class JDBCTest04 {
       public static void main(String[] args) throws IOException {

           //创建Properties集合存放所需配置信息
           Properties properties=new Properties();

           //创建文件字节输入流,获取配置文件信息
           FileInputStream fis=new FileInputStream("D:\\test\\JavaTestFile\\jdbc.txt");

           //将IO获取到的文件加载到集合中
           properties.load(fis);

           //通过Properties集合的key获取集合中的value
           String url=properties.getProperty("url");
           String username=properties.getProperty("username");
           String pwd=properties.getProperty("password");


           //创建jdbc连接对象
           Connection connection=null;
           Statement statement=null;

           try {
               //1.注册驱动
               Class.forName("com.mysql.cj.jdbc.Driver");

               //2.获取连接
               connection= DriverManager.getConnection(url,username,pwd);

               //3.获取数据库操作对象
               statement=connection.createStatement();

               //4.执行sql语句
               statement.executeUpdate("insert into dept(deptno,dname,loc)values(70,‘PROGRAM‘,‘TianJin‘)");

               //5.处理查询结果集
               //
           } catch (ClassNotFoundException | SQLException e) {
               e.printStackTrace();
           }finally {

               //6.释放资源

                if(fis!=null){
                    fis.close();
                }

               if(statement!=null){
                   try {
                       statement.close();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
               }

               if(connection!=null){
                   try {
                       connection.close();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
               }


           }

       }
   } 

JDBC_04_使用Properties集合保存JDBC所需配置信息

标签:code   数据库操作   注册   name   tst   创建文件   连接   获取数据   main   

查看更多关于JDBC_04_使用Properties集合保存JDBC所需配置信息的详细内容...

  阅读:20次