码迷,mamicode.com
首页 > 数据库 > 详细

java 连接数据库测试类

时间:2017-02-22 12:38:12      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:exec   连接数   sql   port   java   print   com   ret   stat   

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ConnectionTest {
    
    public static Connection getConnection() {
        // 定义连接
        Connection connection = null;
        
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    
    public static List<HashMap<String, Object>> getMysqlData() {
        Connection connection = null;
        // 预执行加载
        PreparedStatement preparedStatement = null;
        // 结果集
        ResultSet resultSet = null;
        
        connection = getConnection();
        
        String sqlString = "select * from user";
        
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
        
        try {
            preparedStatement = connection.prepareStatement(sqlString);
            resultSet = preparedStatement.executeQuery();
            HashMap<String, Object> map = null;
            while (resultSet.next()) {
                map = new HashMap<String, Object>();
                map.put("name", resultSet.getString("user_name"));
                list.add(map);
            }
         } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<HashMap<String, Object>> mysqlData = getMysqlData();
        for(HashMap<String, Object> map : mysqlData) {
            System.out.println(map.get("name"));
        }
    }
}

 

java 连接数据库测试类

标签:exec   连接数   sql   port   java   print   com   ret   stat   

原文地址:http://www.cnblogs.com/xu-dong/p/6428180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!