zoukankan      html  css  js  c++  java
  • Java 操作MySQL

          从2011年10月之后就没有用过JAVA了,真是汗颜啊!

          从2012年5月之后就没有写过程序了,真是汗颜!

      今天要做ETL操作,自然第一下就想起了我熟悉的Java。打开eclispe就完全不知道怎么下手了。然后,自己用最简单的例子回忆了一遍Java操作mysql5.0。操作过程基本熟悉之后,我又想起了一个通用的操作代码,所幸在百度文库上面找到了。原作者不详,我只是将源代码贴在下面。

     1 package dao;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.PreparedStatement;
     6 import java.sql.ResultSet;
     7 
     8 public class BaseDao {
     9     public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    10     public static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL";
    11     public static final String USERNAME = "ma";
    12     public static final String PASSWORD = "malei";
    13     
    14     Connection connection = null;
    15     PreparedStatement preparedStatement = null;
    16     ResultSet resultSet = null;
    17     
    18     public Connection getConnection() throws Exception {
    19         Class.forName(DRIVER);
    20         connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
    21         return connection;
    22     }
    23     
    24     public ResultSet executeQuery(String sql) throws Exception {
    25         connection = this.getConnection();
    26         preparedStatement = connection.prepareStatement(sql);
    27         resultSet = preparedStatement.executeQuery();
    28         return resultSet;
    29         
    30     }
    31     
    32     public int executeUpdate(String sql,Object[] obj) throws Exception {
    33         connection = this.getConnection();
    34         preparedStatement = connection.prepareStatement(sql);
    35         for(int i =0;i<obj.length;i++){
    36             preparedStatement.setObject(i+1, obj[i]);
    37         }
    38         return preparedStatement.executeUpdate();
    39     }
    40     
    41     public void closeAll() throws Exception {
    42         if(null != resultSet){
    43             resultSet.close();
    44         }
    45         if(null != preparedStatement){
    46             preparedStatement.close();
    47         }
    48         if(null != connection){
    49             connection.close();
    50         }
    51     }
    52 }

    这是我很早之前初学Java时就见过的模版,很优雅。同时也兼顾了性能PreparedStatement和安全性(防SQL注入)两方面。对于比较简单的数据库操作基本满足要求。

          学习既是训练思维和与遗忘作斗争的过程。但是,我相信忘得快,捡起来会更快!

    !#Never too late to do it now#!
  • 相关阅读:
    SQL——BETWEEN操作符
    SQL——IN操作符
    SQL——LIKE操作符
    SQL——ORDER BY关键字
    SQL——AND、OR运算符
    顺序执行
    流程控制
    集合类型
    字典类型
    字典 in 操作符
  • 原文地址:https://www.cnblogs.com/harrysun/p/2688109.html
Copyright © 2011-2022 走看看