Java连接mysql数据库并执行sql语句

  • Post author:
  • Post category:java


弄这个主要是为了方便测试单个sql的性能,尝试用java连接数据库并查询,将结果的JDBC ResultSet结果集转成List并输出。

import java.sql.*;
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;   //需要这个jar包 mysql-connector-java-5.1.49.jar
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class Test {

    public void action() throws Throwable {

        try {
            int ColumnCount;
            //int RowCount;
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://127.0.0.1:3306/test"; //换成要连接的数据库信息
            String user = "root";
            String password = "password";
            Class.forName ( driver );
            Connection conn = (Connection) DriverManager.getConnection ( url, user, password );
            if (!conn.isClosed ()) {
                System.out.println ( "数据库连接成功:" );
                String sqls = "SELECT * FROM test "; //sql
                PreparedStatement ps = conn.prepareStatement ( sqls );
                ResultSet rs = ps.executeQuery ();
                List list = new ArrayList<String> ();

                ResultSetMetaData rsmd = rs.getMetaData ();
                while (rs.next ()) {
                    ColumnCount = rsmd.getColumnCount ();
                    Map<String,Object> rowData = new HashMap<String,Object>();
                    for (int i = 1; i <= ColumnCount; i++) {
                        rowData.put(rsmd.getColumnName(i),rs.getObject(i));
                    }
                    //将ResultSet结果集写入list
                    list.add(rowData);
                }
                System.out.println ( list );
                ps.close ();
                conn.close ();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace ();
        } catch (SQLException e) {
            e.printStackTrace ();
        }
    }
    public static void main(String[] args)throws Throwable{
        Test test =new Test ();
        test.action();
    }
}

输出结果:

数据库连接成功:
[{ID=53}, {ID=71}]



版权声明:本文为cheng9587原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。