import java.sql.*;
public class JDBCUtils {
private static Connection con = null;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/whsxt?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
String user = "root";
String password = "123456";
con = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println("加载驱动失败");
e.printStackTrace();
}
}
public static String sendSql(String sql) {
Statement statement = null;
try {
statement = con.createStatement();
if (sql.startsWith("select")) {
ResultSet resultSet = statement.executeQuery(sql);
return print(resultSet);
} else {
int i = statement.executeUpdate(sql);
if (i>0){
return "ok";
}else {
return "error";
}
}
} catch (SQLException throwables) {
System.out.println("sql异常");
throwables.printStackTrace();
}
assert statement != null;
close(con, statement);
return "error";
}
/**
* 查询打印
* @param resultSet
* @return
* @throws SQLException
*/
private static String print(ResultSet resultSet) throws SQLException {
// 获取结果集中的元数据 可以得到列总数 找到列名
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
StringBuilder res = new StringBuilder();
while (resultSet.next()){
for (int i = 1; i < columnCount; i++) {
res.append(metaData.getColumnName(i)).append(" ").append(resultSet.getString(i)).append("\n");
}
}
return res.toString();
}
/**
* 关闭资源
* @param connection
* @param statement
*/
public static void close(Connection connection, Statement statement) {
try {
connection.close();
statement.close();
} catch (SQLException throwables) {
System.out.println("释放资源失败");
throwables.printStackTrace();
}
}
}
public static void main(String[] args) {
String s = JDBCUtils.sendSql("select *from user");
System.out.println(s);
}