由于每次连接数据库进行查询比较麻烦,偶尔还需要将查询结果转为json格式的文件,

因此暂时定义一个mysql的类,将这些常用的方法进行封装,便于直接调用(代码如下,个人用,没写什么注释)。

注:导入了https://github.com/stleary/JSON-java的包。

 package connmysql;

 import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; import org.json.JSONObject; public class MySql {
/**
* Define database connection method
* 1. Calling Connect(String db) for Pass in the database name
* that you want to connect to in the MySql.
* 2. Calling Connect(String db,String sql) for Pass in the
* database name that you want to connect to in MySql and
* the MySql query command.
* 3. Calling Close() to close the Database connection.
* 4. Calling ToJson(String db,String sql) to print a json list.
* 5. Calling ToJsonObj(String db,String sql) returns a json object
*/ //Defining database connection parameters
public static final String url = "jdbc:mysql://localhost:3306/";
public static final Properties properties = new Properties();
public Connection conn = null;
public PreparedStatement ppst = null;
public JSONObject json = null;
//Defining database connection methods
public void Connect(String db) {
try {
InputStream input = MySql.class.getClassLoader().getResourceAsStream("connect.properties");
properties.load(input);
//New version driver name:com.mysql.cj.jdbc.Driver
//Old version driver name:com.mysql.jdbc.Driver
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO: handle exception
//System.out.println("Driver loading failed");
e.printStackTrace();
return;
} catch (IOException e) {
//System.out.println("File properties loading failed");
// TODO Auto-generated catch block
e.printStackTrace();
}
db = url+db;
try {
this.conn = DriverManager.getConnection(db, properties);
//System.out.println("Successful database connection"+this.conn);
} catch (SQLException e) {
// TODO: handle exception
//System.out.println("Failed database connection");
e.printStackTrace();
}
} //Defining database connection methods
public void Connect(String db,String sql) {
try {
InputStream input = MySql.class.getClassLoader().getResourceAsStream("connect.properties");
properties.load(input);
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO: handle exception
//System.out.println("Driver loading failed");
e.printStackTrace();
return;
} catch (IOException e) {
//System.out.println("File properties loading failed");
// TODO Auto-generated catch block
e.printStackTrace();
}
db = url+db;
try {
this.conn = DriverManager.getConnection(db, properties);
this.ppst = this.conn.prepareStatement(sql);
//System.out.println("Successful database connection"+this.conn);
//System.out.println("Successful SQL precompiled PreparedStatement"+this.ppst);
} catch (SQLException e) {
// TODO: handle exception
//System.out.println("Failed database connection");
e.printStackTrace();
}
} //Close the database connection
public void Close() {
try {
this.conn.close();
//System.out.println("Successful close database connection");
} catch (SQLException e) {
// TODO Auto-generated catch block
//System.out.println("Failed close database connection");
e.printStackTrace();
}
}
public void ToJson(String db,String sql) {
if(!(sql.startsWith("select") || sql.startsWith("SELECT"))) {
System.out.println("Please pass in a database query statement");
return;
}
MySql mysql = new MySql();
JSONObject jsonobj = new JSONObject();
ResultSet result = null;
try {
mysql.Connect(db,sql);
result = mysql.ppst.executeQuery();
while(result.next()) {
ResultSetMetaData rsmd = result.getMetaData();
Map<String,String> map = new HashMap<>();
for(int i = 1; i <= rsmd.getColumnCount(); i++) {
map.put(rsmd.getColumnLabel(i), result.getString(i));
jsonobj.put(result.getString("id"), map);
}
}
System.out.println(jsonobj.toString());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public JSONObject ToJsonObj(String db,String sql) {
if(!(sql.startsWith("select") || sql.startsWith("SELECT"))) {
System.out.println("Please pass in a database query statement");
return (new JSONObject());
}
MySql mysql = new MySql();
JSONObject jsonobj = new JSONObject();
ResultSet result = null;
try {
mysql.Connect(db,sql);
result = mysql.ppst.executeQuery();
while(result.next()) {
ResultSetMetaData rsmd = result.getMetaData();
Map<String,String> map = new HashMap<>();
for(int i = 1; i <= rsmd.getColumnCount(); i++) {
map.put(rsmd.getColumnLabel(i), result.getString(i));
jsonobj.put(result.getString("id"), map);
}
}
this.json = jsonobj;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this.json;
}
}

测试一:

 package test;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import connmysql.MySql; public class MysqlTest01 { public static void main(String[] args) {
// TODO Auto-generated method stub
MySql mysql = new MySql();
try {
String sql = "INSERT INTO student ( sname, sgender, address ) VALUES ( '孙六', '女', '信阳' )";
mysql.Connect("testdb",sql);
Connection conn = mysql.conn;
PreparedStatement ppst = mysql.ppst;
System.out.println("Successful database Insert update\t"+ppst.executeUpdate());
sql = "delete from student where sname='孙六'";
ppst = conn.prepareStatement(sql);
System.out.println("Successful database delete update\t"+ppst.executeUpdate());
sql = "update student set sname=? where sname=?";
ppst = conn.prepareStatement(sql);
ppst.setString(1,"张三丰");
ppst.setString(2,"张三");
System.out.println("Successful database update\t"+ppst.executeUpdate());
sql = "select id, sname from student";
ppst = mysql.conn.prepareStatement(sql);
ResultSet result=ppst.executeQuery();
while (result.next()) {
System.out.printf("id:%d sanme:%s\n", result.getInt(1),result.getString(2));
}
System.out.println("Successful database select");
mysql.Close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
/* Successful database connectioncom.mysql.cj.jdbc.ConnectionImpl@13acb0d1
Successful SQL precompiled PreparedStatementcom.mysql.cj.jdbc.ClientPreparedStatement: INSERT INTO student ( sname, sgender, address ) VALUES ( '孙六', '女', '信阳' )
Successful database Insert update 1
Successful database delete update 2
Successful database update 0
id:1 sanme:张三丰
id:2 sanme:李四
id:3 sanme:王五
id:5 sanme:张三丰
id:6 sanme:李四
id:7 sanme:王五
Successful database select
Successful close database connection*/
}

测试二:

 package test;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import connmysql.MySql; public class MysqlTest02 { public static void main(String[] args) {
// TODO Auto-generated method stub
MySql mysql = new MySql();
try {
mysql.Connect("testdb","sql");
Connection conn = mysql.conn;
String sql = "INSERT INTO student ( sname, sgender, address ) VALUES ( '孙六', '女', '信阳' )";
PreparedStatement ppst = conn.prepareStatement(sql);
System.out.println("Successful database Insert update\t"+ppst.executeUpdate());
sql = "delete from student where sname='孙六'";
ppst = conn.prepareStatement(sql);
System.out.println("Successful database delete update\t"+ppst.executeUpdate());
sql = "update student set sname=? where sname=?";
ppst = conn.prepareStatement(sql);
ppst.setString(1,"张三丰");
ppst.setString(2,"张三");
System.out.println("Successful database update\t"+ppst.executeUpdate());
sql = "select id, sname from student";
ppst = mysql.conn.prepareStatement(sql);
ResultSet result=ppst.executeQuery();
while (result.next()) {
System.out.printf("id:%d sanme:%s\n", result.getInt(1),result.getString(2));
}
System.out.println("Successful database select");
mysql.Close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
/* Successful database connectioncom.mysql.cj.jdbc.ConnectionImpl@b62fe6d
Successful SQL precompiled PreparedStatementcom.mysql.cj.jdbc.ClientPreparedStatement: sql
Successful database Insert update 1
Successful database delete update 1
Successful database update 0
id:1 sanme:张三丰
id:2 sanme:李四
id:3 sanme:王五
id:5 sanme:张三丰
id:6 sanme:李四
id:7 sanme:王五
Successful database select
Successful close database connection*/
}

测试三:

 package test;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream; import connmysql.MySql; public class MysqlTest03 { public static void main(String[] args) {
// TODO Auto-generated method stub
String sql = "select id, sname from student";
// 使用一个Stream对象接收成员变量json的String返回即可写入本地文件。
MySql mysql = new MySql();
System.out.println("ToJson method print");
mysql.ToJson("testdb", sql);
System.out.println("ToJsonObj method print");
mysql.ToJsonObj("testdb", sql);
System.out.println(mysql.json.toString());
File file = new File("TestDir/des.json");
try {
if (!file.exists()) {
file.createNewFile();
}
String str = mysql.json.toString();
byte[] buffer = str.getBytes();
OutputStream out = new FileOutputStream(file);
out.write(buffer, 0, buffer.length);
System.out.println("Written to local JSON file");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* ToJson method print
{"1":{"sname":"张三丰","id":"1"},"2":{"sname":"李四","id":"2"},"3":{"sname":"王五","id":"3"},"5":{"sname":"张三丰","id":"5"},"6":{"sname":"李四","id":"6"},"7":{"sname":"王五","id":"7"}}
ToJsonObj method print
{"1":{"sname":"张三丰","id":"1"},"2":{"sname":"李四","id":"2"},"3":{"sname":"王五","id":"3"},"5":{"sname":"张三丰","id":"5"},"6":{"sname":"李四","id":"6"},"7":{"sname":"王五","id":"7"}}
Written to local JSON file*/
}

connect.properties文件:

#Mysql
user=""
password=""
useSSL=false
serverTimezone=UTC
verifyServerCertifate=false

des.json文件:

{"1":{"sname":"张三丰","id":"1"},"2":{"sname":"李四","id":"2"},"3":{"sname":"王五","id":"3"},"5":{"sname":"张三丰","id":"5"},"6":{"sname":"李四","id":"6"},"7":{"sname":"王五","id":"7"}}

自定义mysql类用于快速执行数据库查询以及将查询结果转为json文件的更多相关文章

  1. 自定义 Mysql 类 与 自定义 异常类

    import MySQLdb class MyExcept(Exception): ''' 常见做法定义异常基类,然后在派生不同类型的异常 ''' def __init__(self, *args): ...

  2. mysql 命令行快速将数据库转移到另一个服务器中(数据库备份还原)

    想将A服务器中的数据库快速转移到B服务器中,一般是先从A服务器中备份下来,下载备份数据,还原到B服务器中.使用phpMyAdmin备份和还原针对数据量很小的情况下很方便,数据量大的话很容易中断失败. ...

  3. mysql搭建亿级cmd5数据库,毫秒级查询 完全过程

    前言: 最近也在玩数据库,感觉普通机子搞数据库,还是差了点,全文查找,慢的要查一分钟更久. 但是搞cmd5库很不错,亿级数据库,毫秒级. qq 944520563好吧,下面开始,首先你得需要一个mys ...

  4. mysql快速导出数据库ER图和数据字典(附navicat11安装教程及资源)

    ♣ mysql使用navicat11快速导出数据库ER图 ♣ mysql使用navicat11快速导出数据库数据字典 ♣ navicat11 for mysql (这里是mysql5.7.12)专业版 ...

  5. C#操作SqlServer MySql Oracle通用帮助类Db_Helper_DG(默认支持数据库读写分离、查询结果实体映射ORM)

    [前言] 作为一款成熟的面向对象高级编程语言,C#在ADO.Net的支持上已然是做的很成熟,我们可以方便地调用ADO.Net操作各类关系型数据库,在使用了多年的Sql_Helper_DG后,由于项目需 ...

  6. 第二百八十八节,MySQL数据库-索引、limit分页、执行计划、慢日志查询

    MySQL数据库-索引.limit分页.执行计划.慢日志查询 索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构.类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获 ...

  7. MySQL数据库之单表查询中关键字的执行顺序

    目录 MySQL数据库之单表查询中关键字的执行顺序 1 语法顺序 2 执行顺序 3 关键字使用语法 MySQL数据库之单表查询中关键字的执行顺序 1 语法顺序 select distinct from ...

  8. CodeIgniter框架——数据库类(配置+快速入门)

    CodeIgniter用户指南——数据库类 数据库配置 入门:用法举例 连接数据库 查询 生成查询结果 查询辅助函数 Active Record 类 事务 表格元数据 字段元数据 自定义函数调用 查询 ...

  9. 【JDBC】Java 连接 MySQL 基本过程以及封装数据库工具类

    一. 常用的JDBC API 1. DriverManager类 : 数据库管理类,用于管理一组JDBC驱动程序的基本服务.应用程序和数据库之间可以通过此类建立连接.常用的静态方法如下 static ...

随机推荐

  1. .net core在Linux下获取AD域信息

    .net core在Linux下获取AD域信息 .net Core 2.1.4 .net core现在System.DirectoryServices只支持Windows平台下使用. 参考: http ...

  2. js精度溢出解决方案

    一般参数值不能超过16位.如果超出16都是用0替代,导致我们查询不到自己想要的结果. 遇到此问题我们做如下修改 自己写属性 原始的: <a href="javascript:void( ...

  3. 出现 The processing instruction target matching "[xX][mM][lL]" is not allowed错误

    错误原因与解决办法: 这个错误的原因是因为xml的开始有多余的空格造成的,只要把多余的空格删除就没有问题了. xml开始部分写注释也会出现此问题. 本文出自:艺意

  4. [CF833B] The Bakery

    Description 将一个长度为n的序列分为k段 使得总价值最大一段区间的价值表示为区间内不同数字的个数 \(n\leq 35000,k\leq 50,1\leq a_i\leq n\) Solu ...

  5. .8-浅析webpack源码之Tapable介绍

    Tapable工具 完成webpack默认参数注入后,下一步虽然是 new Compiler() ,但是这东西不是一下可以讲完的,复杂的一批. 不如先从工具入手,分块讲解compiler,首先来看看事 ...

  6. typeof() 和 GetType()区是什么

    1.typeof(x)中的x,必须是具体的类名.类型名称等,不可以是变量名称. 2.GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,它的作用和typeof() ...

  7. html特殊字体显示

    1.下载需要显示的ttf字体. 2.css样式调用. /* 微软雅黑 */ @font-face { font-family: microsoftyahei; src: url('${pageCont ...

  8. elasticsearch6.7 05. Document APIs(7)Update By Query API

    6.Update By Query API _update_by_query 接口可以在不改变 source 的情况下对 index 中的每个文档进行更新.这对于获取新属性或其他联机映射更改很有用.以 ...

  9. 【RabbitMQ】5、RabbitMQ任务分发机制

    当有Consumer需要大量的运算时,RabbitMQ Server需要一定的分发机制来balance每个Consumer的load.接下来我们分布讲解. 应用场景就是RabbitMQ Server会 ...

  10. kafka安装与简单使用

    一.kafka安装 安装是非常简单的,现在推荐安装0.8的版本,这个版本是非常稳定的,而且公司里面也多用此版本. 简单的安装: 这个是我使用的版本,kafka_2.11-0.8.2.2.tgz 直接t ...