1.原生JDBC连接
(1) 引入包
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- oralle -->
<dependency>
<groupId>org.clojars.zentrope</groupId>
<artifactId>ojdbc</artifactId>
<version>11.2.0.3.0</version>
</dependency>
<!--postgresql驱动-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
(2) 获取连接
driverClass:
oracle.jdbc.driver.OracleDriver
com.mysql.cj.jdbc.Driver
url :
jdbc:oracle:thin:@localhost:1521/orcl
jdbc:mysql://localhost:3306/mydb
public static Connection getConn(String driverClass,String url,String user,String pwd) {
Connection conn = null;
try {
Class.forName(driverClass);
conn = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
(3) 获取某张表的所有字段
// 获取某个表的所有字段
public static List<String> getAllField(DatasourceProperty d,String tabName) {
List<String> list = new LinkedList<>();
Connection conn = getConn(d.getDriverClass(),d.getConnUrl(),d.getUserName(),d.getPwd());
try {
String sql = "";
if(d.getDbType() == 0){
sql = "select t.column_name field from user_col_comments t where t.table_name = '"+tabName+"'";
}else if(d.getDbType() == 1){
sql = "show full columns from "+tabName+";";
}
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) { // 判断是否还有下一个数据
// 根据字段名获取相应的值
String field = rs.getString("field");
//输出查到的记录的各个字段的值
list.add(field);
}
} catch (SQLException e) {
System.out.printf("sql语法错误");
e.printStackTrace();
}finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
2 FileReader直接读取文件乱码问题
(1) 原始代码这样写的,有些文件可以正常读,但是文件编码换了就读出来乱码了
FileReader fr = null;
BufferedReader bf = null;
try{
fr = new FileReader("C:/Users/Lenovo/Desktop/myfile/englist.txt");
bf = new BufferedReader(fr);
String s = bf.readLine();
while(null != s){
System.out.println(s);
s = bf.readLine();
}
}catch (FileNotFoundException e){
System.out.println("没找到文件");
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
if(null != fr){
fr.close();
}
if(null != bf){
bf.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
文件是GB2312编码,读出来乱码
读取文件那块改了一下就可以都出来了
fr = new FileReader("C:/Users/Lenovo/Desktop/myfile/novels/mfc/all.txt");
bf = new BufferedReader(fr);
FileInputStream fis = new FileInputStream("C:/Users/Lenovo/Desktop/myfile/novels/mfc/all.txt");
InputStreamReader isr = new InputStreamReader(fis, "GB2312");
bf = new BufferedReader(isr);
(3) 多线程
获取系统内核数量: Runtime.getRuntime().availableProcessors()
在创建固定线程池的时候使用:
ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
(4) pom文件
optional属性的功能:本jar包只能自己使用,别人引入本项目不会引入此包
Maven中的dependencyManagement元素提供了一种管理依赖版本号的方式。在dependencyManagement元素中声明所依赖的jar包的版本号等信息,那么所有子项目再次引入此依赖jar包时则无需显式的列出版本号。Maven会沿着父子层级向上寻找拥有dependencyManagement 元素的项目,然后使用它指定的版本号。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
dependencyManagement中定义的只是依赖的声明,并不实现引入,因此子项目需要显式的声明需要用的依赖。
原文链接:https://blog.csdn.net/weixin_42114097/article/details/81391024
3 使用httpClient
(1)引入jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
(2)直接使用:
执行get请求
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http GET请求
HttpGet httpGet = new HttpGet(url);
// 设置连接属性
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30000).build();
httpGet.setConfig(requestConfig);
try {
// 执行请求
response = httpclient.execute(httpGet);
System.out.println(response.getStatusLine());
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
return Result.ok("ok",content);
}
}catch(Exception e){
e.printStackTrace();
return Result.error(e.getMessage());
}
执行post请求:
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http post请求
HttpPost post = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30000).build();
post.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
// 执行请求
post.setHeader("Content-Type", "application/json");
if (CollectionUtils.isNotEmpty(params)){
JSONObject jo = new JSONObject();
//增加参数
addParam(params,jo);
post.setEntity(new StringEntity(jo.toString(), ContentType.APPLICATION_JSON));
}else {
post.setEntity(new StringEntity(null, ContentType.APPLICATION_JSON));
}
//创建响应对象
response = httpClient.execute(post);
/**
* 由于响应接口返回的是一个字符串,因此需要转换
* 响应体数据封装在HttpEntity对象中
*/
String result = EntityUtils.toString(response.getEntity(), "utf-8");
return Result.ok("ok",result);
}catch(Exception e){
e.printStackTrace();
return Result.error(e.getMessage());
}
private JSONObject addParam(Map < String, Object > map, JSONObject jsonObject) {
for (Map.Entry < String, Object > entry: map.entrySet()) {
jsonObject.put(entry.getKey(), entry.getValue());
}
return jsonObject;
}
有时项目访问https需要验证证书,下面是跳过证书验证创建连接方式:
public static CloseableHttpClient buildDefaultHttpClientTrustSSL(){
SSLContext sslContext = null;
try {
sslContext = SSLContextBuilder.create().setProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
} catch (Exception e) {
e.printStackTrace();
}
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.setConnectionRequestTimeout(30000)
.setContentCompressionEnabled(true)
.build();
return HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
}
此时创建httpclient时调用此方法即可:
CloseableHttpClient httpClient = buildDefaultHttpClientTrustSSL();