zoukankan      html  css  js  c++  java
  • Android 之JDBC

    JDBC(Java DataBase Connectivity)是使用 Java 存取数据库系统的标准解决方案,它将不同数据库间各自差异API与标准 SQL语句分开看待,实现数据库无关的 Java操作接口。

    JDBC程序访问数据库的步骤 

    步骤一:加载JDBC驱动程序:Class.forName("com.mysql.jdbc.Driver");Oracle10g:oracle.jdbc.driver.OracleDriver;MySQL5:com.mysql.jdbc.Driver;SQLServer2005:com.microsoft.sqlserver.jdbc.SQLServerDriver
    步骤二:提供连接参数:URL,USERNAME, PASSWORD:不同数据库产品的连接URL不同
    Oracle10g:jdbc:oracle:thin:@主机名:端口:数据库SID
    jdbc:oracle:thin:@localhost:1521:ORCL
    MySQL5:jdbc:mysql://主机名:端口/数据库名
    jdbc:mysql://localhost:3306/test       
    SQLServer2005:jdbc:sqlserver://主机名:端口:DatabaseName=库名
    jdbc:sqlserver://localhost:1433:DatabaseName=BookDB
    步骤三:建立一个数据库的连接:connection=DriverManager.getConnection(URL,USERNAME, PASSWORD);
    步骤四:创建一个statement:preparedStatement=connection.prepareStatement(sql);
    步骤五:执行SQL语句:result=preparedStatement.executeUpdate();
    步骤六:处理结果:flag=result>0?true:false;return flag;
    步骤七:关闭JDBC对象:if(resultSet!=null){resultSet.close();}if(preparedStatement!=null){preparedStatement.close();}if(connection!=null){connection.close();}
      1 package com.jdbc.dbUtils;
      2 
      3 import java.lang.reflect.Field;
      4 import java.sql.Connection;
      5 import java.sql.DriverManager;
      6 import java.sql.PreparedStatement;
      7 import java.sql.ResultSet;
      8 import java.sql.ResultSetMetaData;
      9 import java.sql.SQLException;
     10 import java.util.ArrayList;
     11 import java.util.HashMap;
     12 import java.util.List;
     13 import java.util.Map;
     14 
     15 import com.jdbc.dbUtils.dormain.UserInfo;
     16 
     17 
     18 
     19 public class JDBCutils {
     20 
     21     private final String USERNAME="root";
     22     private final String PASSWORD="admin";
     23     private final String DRIVER="com.mysql.jdbc.Driver";
     24     private final String URL="jdbc:mysql://localhost:3306/mydb";
     25      
     26     private Connection connection;
     27     private PreparedStatement preparedStatement;
     28     private ResultSet resultSet;
     29     
     30     public JDBCutils() {
     31         try {
     32             Class.forName(DRIVER);//注册驱动
     33             System.out.println("成功注册驱动");
     34             
     35         } catch (Exception e) {
     36             // TODO: handle exception
     37         }
     38     }
     39 
     40     public Connection getConnection(){
     41         try {
     42             connection=DriverManager.getConnection(URL,USERNAME, PASSWORD);
     43         } catch (Exception e) {
     44             // TODO: handle exception
     45             e.printStackTrace();
     46         }
     47         return connection;
     48     }
     49     //增删改
     50     public boolean updateByPreparedStatement(String sql,List<Object> params)throws SQLException {
     51         boolean flag=false;
     52         int result=-1;//执行增删改操作的时候所影响的行数
     53         int index=1;//占位符的第一个位置
     54         preparedStatement=connection.prepareStatement(sql);
     55         if(params!=null&&!params.isEmpty()){
     56             for (int i = 0; i < params.size(); i++) {
     57                 preparedStatement.setObject(index++, params.get(i));
     58             }
     59         }
     60         result=preparedStatement.executeUpdate();
     61         flag=result>0?true:false;
     62         return flag;
     63     }
     64     //查询 返回单条记录
     65     public Map<String,Object> findSimpleResult(String sql,List<Object> params) throws SQLException{
     66         Map<String,Object> map=new HashMap<String,Object>();
     67         int index=1;//占位符的第一个位置
     68         preparedStatement=connection.prepareStatement(sql);
     69         if(params!=null&&!params.isEmpty()){
     70             for (int i = 0; i < params.size(); i++) {
     71                 preparedStatement.setObject(index++, params.get(i));
     72             }
     73         }
     74         resultSet=preparedStatement.executeQuery();
     75         ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
     76         int col_len=resultSetMetaData.getColumnCount();//得到数据库表的列
     77         while(resultSet.next()){
     78             for (int i = 0; i < col_len; i++) {
     79                 String col_name=resultSetMetaData.getColumnName(i+1);
     80                 Object col_val=resultSet.getObject(col_name);
     81                 if(col_val==null){
     82                     col_val="";
     83                 }
     84                 map.put(col_name,col_val);
     85             }
     86         }
     87         return map;
     88         
     89     }
     90     //查询 返回多条记录
     91     public List<Map<String,Object>> findMultiResult(String sql,List<Object> params) throws SQLException{
     92         List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
     93         int index=1;//占位符的第一个位置
     94         preparedStatement=connection.prepareStatement(sql);
     95         if(params!=null&&!params.isEmpty()){
     96             for (int i = 0; i < params.size(); i++) {
     97                 preparedStatement.setObject(index++, params.get(i));
     98             }
     99         }
    100         resultSet=preparedStatement.executeQuery();
    101         ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
    102         int col_len=resultSetMetaData.getColumnCount();//得到数据库表的列名
    103         while(resultSet.next()){
    104             Map<String,Object>map=new HashMap<String,Object>();
    105             for (int i = 0; i < col_len; i++) {
    106                 String col_name=resultSetMetaData.getColumnName(i+1);
    107                 Object col_val=resultSet.getObject(col_name);
    108                 if(col_val==null){
    109                     col_val="";
    110                 }
    111                 map.put(col_name,col_val);
    112             }
    113             list.add(map);
    114         }
    115         return list;
    116         
    117     }
    118     //jdbc的封装也可以采用反射机制
    119     public <T> T findSimpReflectResult(String sql,List<Object> params,Class<T> cls) throws Exception{
    120         T resObj=null;
    121         int index=1;//占位符的第一个位置
    122         preparedStatement=connection.prepareStatement(sql);
    123         if(params!=null&&!params.isEmpty()){
    124             for (int i = 0; i < params.size(); i++) {
    125                 preparedStatement.setObject(index++, params.get(i));
    126             }
    127         }
    128         resultSet=preparedStatement.executeQuery();
    129         ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
    130         int col_len=resultSetMetaData.getColumnCount();//得到数据库表的列名
    131         while(resultSet.next()){
    132             resObj=cls.newInstance();//通过反射机制创建实例
    133             for (int i = 0; i < col_len; i++) {
    134                 String col_name=resultSetMetaData.getColumnName(i+1);
    135                 Object col_val=resultSet.getObject(col_name);
    136                 if(col_val==null){
    137                     col_val="";
    138                 }
    139                 Field field=cls.getDeclaredField(col_name);
    140                 field.setAccessible(true);//打开访问javabean的私有权限
    141                 field.set(resObj, col_val);
    142             }
    143         }
    144         return resObj;
    145     }
    146     public <T> List<T> findMultiReflectResult(String sql,List<Object> params,Class<T> cls) throws Exception{
    147         List<T> list=new ArrayList<T>();
    148         int index=1;//占位符的第一个位置
    149         preparedStatement=connection.prepareStatement(sql);
    150         if(params!=null&&!params.isEmpty()){
    151             for (int i = 0; i < params.size(); i++) {
    152                 preparedStatement.setObject(index++, params.get(i));
    153             }
    154         }
    155         resultSet=preparedStatement.executeQuery();
    156         ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
    157         int col_len=resultSetMetaData.getColumnCount();//得到数据库表的列名
    158         while(resultSet.next()){
    159             T resObj=cls.newInstance();//通过反射机制创建实例
    160             for (int i = 0; i < col_len; i++) {
    161                 String col_name=resultSetMetaData.getColumnName(i+1);
    162                 Object col_val=resultSet.getObject(col_name);
    163                 if(col_val==null){
    164                     col_val="";
    165                 }
    166                 Field field=cls.getDeclaredField(col_name);
    167                 field.setAccessible(true);//打开访问javabean的私有权限
    168                 field.set(resObj, col_val);
    169             }
    170             list.add(resObj);
    171         }
    172         return list;
    173     }
    174     public void releaseConnection() throws SQLException{
    175         if(resultSet!=null){
    176             resultSet.close();
    177         }
    178         if(preparedStatement!=null){
    179             preparedStatement.close();
    180         }
    181         if(connection!=null){
    182             connection.close();
    183         }
    184     }
    185     public static void main(String[] args) throws Exception {
    186         // TODO Auto-generated method stub
    187         JDBCutils jdbc=new JDBCutils();
    188         jdbc.getConnection();
    189         List<Object> params=new ArrayList<Object>();
    190     
    191         /*    params.add("fjf");
    192         params.add("123");
    193         params.add("fanjingfang");
    194         String sql="insert into userinfo(username,password,realname)values(?,?,?)";
    195         boolean flag=jdbc.updateByPreparedStatement(sql, params);
    196         System.out.println(flag);
    197         params.add(1);
    198         String sql="select * from userinfo where id=?";
    199         Map<String,Object> m=jdbc.findSimpleResult(sql, params);
    200         System.out.println(m);*/
    201         
    202         /*String sql2="select * from userinfo ";
    203         List<Map<String,Object>> list=jdbc.findMultiResult(sql2, null);
    204         System.out.println(list);*/
    205         
    206     /*    params.add(1);
    207         String sql3="select * from userinfo where id=? ";
    208         UserInfo u=jdbc.findSimpReflectResult(sql3, params,UserInfo.class);
    209         System.out.println(u);*/
    210         
    211         String sql4="select * from userinfo ";
    212         List<UserInfo> list=jdbc.findMultiReflectResult(sql4, null,UserInfo.class);
    213         System.out.println(list);
    214     }
    215 
    216 }
    View Code
     
  • 相关阅读:
    EntityFramework优缺点
    领导者与管理者的区别
    七个对我最好的职业建议(精简版)
    The best career advice I’ve received
    Difference between Stored Procedure and Function in SQL Server
    2015年上半年一次通过 信息系统项目管理师
    Difference between WCF and Web API and WCF REST and Web Service
    What’s the difference between data mining and data warehousing?
    What is the difference between a Clustered and Non Clustered Index?
    用new创建函数的过程发生了什么
  • 原文地址:https://www.cnblogs.com/mlj5288/p/4969519.html
Copyright © 2011-2022 走看看