/**
* 1、验证数据库连通性
* 2、验证SQL执行是否成功
* @date 2021/2/1 19:05
*/
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JDBCTool {
public static Connection getConnection(String driver,String url,String name,String pwd){
try{
Class.forName(driver);
Connection conn=DriverManager.getConnection(url,name,pwd);//获取连接对象
return conn;
}catch(ClassNotFoundException e){
System.out.println("ClassNotFoundException!");
//e.printStackTrace();
return null;
}catch(SQLException e){
//e.printStackTrace();
return null;
}
}
public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
try{
if(rs!=null){
rs.close();
}
}catch(SQLException e){
// e.printStackTrace();
}
try{
if(ps!=null){
ps.close();
}
}catch(SQLException e){
//e.printStackTrace();
}
try{
if(conn!=null){
conn.close();
}
}catch(SQLException e){
// e.printStackTrace();
}
}
public static Map<String,Object> checkConn(String driver, String url, String name, String pwd){
Map<String,Object> rs =new HashMap();
Connection cc=JDBCUtilTool.getConnection(driver,url,name,pwd);
try {
if(cc!=null){
if(!cc.isClosed()){
rs.put("resultCode",0);
rs.put("resultMsg","数据库连接成功!");
}
}else{
rs.put("resultCode",-1);
rs.put("resultMsg","数据库连接失败!");
}
} catch (SQLException e) {
rs.put("resultCode",-1);
rs.put("resultMsg",e);
}
return rs;
}
private static List convertList(ResultSet rs) throws SQLException{
List list = new ArrayList();
ResultSetMetaData md = rs.getMetaData();//获取键名
int columnCount = md.getColumnCount();//获取行的数量
while (rs.next()) {
Map rowData = new HashMap();//声明Map
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
}
list.add(rowData);
}
return list;
}
public static Map<String,Object> checkSql(String driver, String url, String name, String pwd,String sql){
Map<String,Object> rs =new HashMap();
Connection cc=JDBCUtilTool.getConnection(driver,url,name,pwd);
try {
if(cc!=null){
Statement statement = cc.createStatement();
ResultSet rsValue = statement.executeQuery(sql);
rs.put("resultCode",0);
rs.put("resultMsg",convertList(rsValue).toString());
//System.out.println("查询出来数据"+convertList(rsValue).toString());
}else{
rs.put("resultCode",-1);
rs.put("resultMsg","数据库连接失败!");
}
} catch (SQLException e) {
rs.put("resultCode",-1);
rs.put("resultMsg",e);
}
return rs;
}
public static void main(String[] args)
{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://192.168.2.196:3307/mydb";
String name="121232";
String pwd="1312313";
String sql="select * from tp_busi_attr";
Map cc=JDBCUtilTool.checkConn(driver,url,name,pwd);
System.out.println(cc.toString());
Map ss=JDBCUtilTool.checkSql(driver,url,name,pwd,sql);
System.out.println(ss.toString());
}
}