MysqlJdbcUtil01

2019-08-26  本文已影响0人  jinhm007

package com.test.demo.autodemo;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import java.sql.*;

import java.util.*;

public class MysqlJdbcUtil01 {

//创建数据库连接

    static Connectionconn =null;

    //创建预编译语句对象

    static Statementpstmt =null;

    //创建一个结果集

    static ResultSetresult =null;

    //执行的SQL

    private static  StringSQL_STATEMENT="select t1.aaa,t1.bbb,t1.ccc from demo t1  join (select * from demo) t2 on t1.aaa=t2.aaa and \n" +

"t1.aaa=t2.aaa and  t1.ccc =t2.ccc where t1.action='I' and t2.ACTION='D'";

    private  static List>list=new ArrayList<>();

    private static final Loglog = LogFactory.getLog(MysqlJdbcUtil01.class);

    private static ResourceBundlebundle;

    private static void getSQL(){

bundle = ResourceBundle.getBundle("jdbc");

        SQL_STATEMENT =bundle.getString("SQL_STATEMENT");

        System.out.println(SQL_STATEMENT);

    }

/**

* 初始化数据库连接驱动

*/

    private static void initJdbc() {

try {

Class.forName("com.mysql.jdbc.Driver"); //加载驱动程序

            String url ="jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8"; //数据库连接信息

            String user ="root"; //数据库用户名

            String pass ="666888"; //数据库密码

            conn = DriverManager.getConnection(url, user, pass); //获取连接

        }catch (ClassNotFoundException e) {

e.printStackTrace();

        }catch (SQLException e) {

e.printStackTrace();

        }

}

public static List>queryTable()throws SQLException {

initJdbc();

            Statement stmt =conn.createStatement();

            ResultSet rs = stmt.executeQuery(SQL_STATEMENT);

            System.out.println("\n== Begin Query Results ======================");

            ResultSetMetaData md = rs.getMetaData();

            int columnCount = md.getColumnCount();

            System.out.println(columnCount);

            while (rs.next()) {

//  System.out.println(rs.getString(1));

                Map rowData =new HashMap<>();

                for (int k =1; k <=columnCount; k++) {

rowData.put(md.getColumnName(k),rs.getObject(k));

                }

list.add(rowData);

            }

System.out.println(list);

            return  list;

        }

public static void main(String[] args)throws SQLException {

// getSQL();

        queryTable();

    }

}

上一篇下一篇

猜你喜欢

热点阅读