由于每次连接数据库进行查询比较麻烦,偶尔还需要将查询结果转为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. ES启动报错之引导检测失败

    [--16T18::,][ERROR][o.e.b.Bootstrap ] [node-] node validation exception [] bootstrap checks failed [ ...

  2. 给mysql添加一个只有某个数据库查询权限的用户

    添加用户: insert into mysql.user(Host,User,Password,ssl_cipher,x509_issuer,x509_subject) values ("1 ...

  3. Animate.css(一款有意思的CSS3动画库)

    官网:https://daneden.github.io/animate.css/ animate.css 是一款跨浏览器的动画库. 使用方式: 在页面的 <head>中引入样式文件: & ...

  4. 支付宝(alipay)即时到账收款接口开发中的那些事儿

    不会做,看看也可以会,要做好就还是需要多学习 国庆回来就一直没状态,看完<银河护卫队>,印象最深的竟然是只有两句台词的呆萌groot,昨天才休息一天,大耍大吃,今天还是把昨天的知识学习一下 ...

  5. Hyperledger Fabric密码模块系列之BCCSP(五) - 国密算法实现

    Talk is cheap, show me your code. 代码也看了,蛋也扯了,之后总该做点什么.响应国家政策,把我们的国密算法融合进去吧--  先附两张bccsp下国密算法的设计实现图. ...

  6. Android目录结构及作用

    1.add-ons-->Google API .比如GoogleMaps 2.build-tools-->各版本SDK编译工具. 3.docs-->离线开发者文档Android SD ...

  7. 部署DTCMS到Jexus遇到的问题及解决思路--验证码

    上一篇博客我们已经基本完成了部署工作,目前发现了验证码出现500错误,分析其代码,我们可以看到验证码使用的是System.Drawing命名空间下的类库, GDI+ 位图,这个在肯定是平台相关的,所以 ...

  8. 如何在 ASP.NET Core 测试中操纵时间?

    有时候,我们会遇到一些跟系统当前时间相关的需求,例如: 只有开学季才允许录入学生信息 只有到了晚上或者周六才允许备份博客 注册满 3 天的用户才允许进行一些操作 某用户在 24 小时内被禁止发言 很显 ...

  9. Android开发day-01

    http://note.youdao.com/noteshare?id=b7f0d55c1e5eab20bb47e5c58e683611

  10. HDU6095

    Rikka with Competition Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/O ...