由于每次连接数据库进行查询比较麻烦,偶尔还需要将查询结果转为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. 一文了解JAVA虚拟机的重要组成

    JVM是JAVA平台的重要组成之一,因涉及知识点太多,故从以下几个方面对JVM进行浅层面的介绍,如果需要深入理解,推荐学习机械工业出版社的<深入理解JAVA虚拟机>. 请尊重作者劳动成果, ...

  2. 如何用TexturePacker打包素材

    如何用TexturePacker打包素材 TexturePacker是一个非常好用的图片素材打包工具,它能帮助你减少游戏的图片内存使用. 官方下载地址:http://www.codeandweb.co ...

  3. postman传递对象到spring controller的方式

    1.spring Controller @RestController @RequestMapping(value = "/basic/task") public class Ta ...

  4. mybatis教程之原理剖析

    MyBatis是目前非常流行的ORM框架,功能很强大,然而其实现却比较简单.优雅.本文通过代理的方式来看下其实现 方式一:传统API方式 @Test public void add() throws ...

  5. SpringMVC教程2

    接上篇文章-SpringMVC教程1 五.基本操作 1.响应请求的方式 1.1ModeAndView /** * 查询方法 * @return */ @RequestMapping("/qu ...

  6. [总结] LCT学习笔记

    \(emmm\)学\(lct\)有几天了,大概整理一下这东西的题单吧 (部分参考flashhu的博客) 基础操作 [洛谷P1501Tree II] 题意 给定一棵树,要求支持 链加,删边加边,链乘,询 ...

  7. [转]window7下利用DockerToolbox安装Docker

    本文转自:https://blog.csdn.net/qq2712193/article/details/54576313 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blo ...

  8. 获取微信的access_tokey,处理json格式的数据

    #region 获取微信凭证 public string GetAccessToken(string wechat_id) { string accessToken = ""; D ...

  9. C# 单例模式和窗体的单例打开方法

    第一种最简单,但没有考虑线程安全,在多线程时可能会出问题,不过俺从没看过出错的现象,表鄙视我…… public class Singleton{    private static Singleton ...

  10. 【c#】6.0与7.0新特性介绍记录

    c#发展史 引用地址:https://www.cnblogs.com/ShaYeBlog/p/3661424.html 6.0新特性 1.字符串拼接优化 语法格式:$”string {参数}” 解释: ...