java.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;public classConnectionTest {public staticConnection 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();
}returnconnection;
}public static List>getMysqlData() {
Connection connection= null;//预执行加载
PreparedStatement preparedStatement = null;//结果集
ResultSet resultSet = null;
connection=getConnection();
String sqlString= "select * from user";
List> list = new ArrayList>();try{
preparedStatement=connection.prepareStatement(sqlString);
resultSet=preparedStatement.executeQuery();
HashMap map = null;while(resultSet.next()) {
map= new HashMap();
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();
}
}returnlist;
}public static voidmain(String[] args) {
List> mysqlData =getMysqlData();for(HashMapmap : 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