对于刚学习SQL的同学来说,写SQL代码莫过于是一件很痛苦的事,在你没有学习框架技术的时候,你不知道怎么处理繁杂的SQL语句的时候,你很头痛,你不想写一堆无意义的代码,哎,没事,我们今天花十分钟,基于Java手写一个,SQL语句自动生成!
好,废话不多说,上画面:
怎么实现的呢?其实很简单:
实现这个功能,你只需要掌握JDBC的基本手写实现(在不使用框架的基础之上)。
首先,你需要一个集成的JDBC(这里是手写的,所以大家可以根据自己的需求按需求写代码)
注意这里的版本切换,mysql5.X与mysql8.X版本的差异在于连接上的不同,所以一定看清楚了!
package gd;
/**
* author fntp 2020/05/02
*/
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import nide.oi;
public class JDBC {
//实现使用JDBC连接数据库MySQL
public Connection GetConnection(String user ,String password) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
// String url = "jdbc:mysql://localhost:3306/zhiyou_apartment?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String url = "jdbc:mysql://localhost:3306/";
Connection conn = null;
oi yu = new oi();
try {
conn= DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
yu.Tishi("很遗憾", "连接失败!请检查您的账户密码是否正确?如若正确,请检查数据库服务是否打开!");
e.printStackTrace();
}
return conn;
}
public Connection GetConnection(String user ,String password,String database) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
// String url = "jdbc:mysql://localhost:3306/zhiyou_apartment?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String url = "jdbc:mysql://localhost:3306/"+database;
Connection conn = null;
oi yu = new oi();
try {
conn= DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
yu.Tishi("很遗憾", "连接失败!请检查您的账户密码是否正确?如若正确,请检查数据库服务是否打开!");
e.printStackTrace();
}
return conn;
}
//返回所有数据表的字段
public List<String> getColumnNames(String user,String password,String databasename,String tableName) throws Exception {
List<String> columnNames = new ArrayList<>();
//与数据库的连接
PreparedStatement pStemt = null;
String tableSql ="select * from " + tableName;
try {
pStemt = GetConnection(user,password,databasename).prepareStatement(tableSql);
//结果集元数据
ResultSetMetaData rsmd = pStemt.getMetaData();
//表列数
int size = rsmd.getColumnCount();
for (int i = 0; i < size; i++) {
columnNames.add(rsmd.getColumnName(i + 1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (pStemt != null) {
try {
pStemt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return columnNames;
}
// 8.0的写法:获取所有字段
public List<String> getColumnNames_mysql8(String user,String password,String databasename,String tableName) throws Exception {
List<String> columnNames = new ArrayList<>();
//与数据库的连接
PreparedStatement pStemt = null;
String tableSql ="select * from " + tableName;
try {
pStemt = GetConnection_MySQL_8(user,password,databasename).prepareStatement(tableSql);
//结果集元数据
ResultSetMetaData rsmd = pStemt.getMetaData();
//表列数
int size = rsmd.getColumnCount();
for (int i = 0; i < size; i++) {
columnNames.add(rsmd.getColumnName(i + 1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (pStemt != null) {
try {
pStemt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return columnNames;
}
// select SCHEMA_NAME from information_schema.schemata
// 返回所有数据库的名称(5.0版本代码写法)
public List<String> getDatabasenames(String user,String password) throws Exception {
List<String> DatabaseNames = new ArrayList<>();
//与数据库的连接
PreparedStatement pStemt = null;
String tableSql ="select SCHEMA_NAME from information_schema.schemata;" ;
pStemt = GetConnection(user,password).prepareStatement(tableSql);
//结果集元数据
// ResultSetMetaData rsmd = pStemt.getMetaData();
ResultSet rs=pStemt.executeQuery();
//表列数
while(rs.next()){
DatabaseNames.add(rs.getString(1));
}
return DatabaseNames;
}
// 返回所有数据库的名称
public List<String> getDatabasenames_mysql8(String user,String password) throws Exception {
List<String> DatabaseNames = new ArrayList<>();
//与数据库的连接
PreparedStatement pStemt = null;
String tableSql ="select SCHEMA_NAME from information_schema.schemata;" ;
pStemt = GetConnection_MySQL_8(user,password).prepareStatement(tableSql);
//结果集元数据
// ResultSetMetaData rsmd = pStemt.getMetaData();
ResultSet rs=pStemt.executeQuery();
//表列数
while(rs.next()){
DatabaseNames.add(rs.getString(1));
}
return DatabaseNames;
}
// 返回所有表的名字
public List<String> getAllTableNames( String user, String password,String databasename) throws Exception {
List<String>tableNames = new ArrayList<String>();
if ( GetConnection(user,password) != null) {
try {
DatabaseMetaData dbmd = GetConnection(user,password).getMetaData();
// 表名列表
ResultSet rest = dbmd.getTables(databasename, null, null, new String[] {
"TABLE" });
// 输出 table_name
while (rest.next()) {
tableNames.add(rest.getString("TABLE_NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return tableNames;
}
// 返回所有数据表的名单mysql8.0写法
public List<String> getAllTableNames_mysql8( String user, String password,String databasename) throws Exception {
List<String>tableNames = new ArrayList<String>();
if ( GetConnection_MySQL_8(user,password) != null) {
try {
DatabaseMetaData dbmd =GetConnection_MySQL_8(user,password).getMetaData();
// 表名列表
ResultSet rest = dbmd.getTables(databasename, null, null, new String[] {
"TABLE" });
// 输出 table_name
while (rest.next()) {
tableNames.add(rest.getString("TABLE_NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return tableNames;
}
// public static void main(String[] args) throws Exception {
// List yu=new JDBC().getAllTableNames("root", "root","bookmanager");
// for(int a=0;a
// System.out.println(yu.get(a));
// }
// }
// 连接数据库8.0的连接
public Connection GetConnection_MySQL_8(String user ,String password)throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = null;
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy?useSSL=false&serverTimezone=GMT%2B8",user,password);
return conn;
}
// 复写连接方法
public Connection GetConnection_MySQL_8(String user ,String password,String databasename)throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = null;
conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/"+databasename+"?useSSL=false&serverTimezone=GMT%2B8",user,password);
return conn;
}
// 获取mysql8.0的所有数据表
public List<String> getColumnNames_mysql8_cloumn(String user,String password,String databasename,String tableName) throws Exception {
List<String> columnNames = new ArrayList<>();
//与数据库的连接
PreparedStatement pStemt = null;
String tableSql ="select * from " + tableName;
try {
pStemt = GetConnection_MySQL_8(user,password,databasename).prepareStatement(tableSql);
//结果集元数据
ResultSetMetaData rsmd = pStemt.getMetaData();
//表列数
int size = rsmd.getColumnCount();
for (int i = 0; i < size; i++) {
columnNames.add(rsmd.getColumnName(i + 1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (pStemt != null) {
try {
pStemt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return columnNames;
}
}
紧接着就是java的swt组件的操作使用,控件的使用涉及GUI,GUI大家应该都熟悉,我就不多说了!直接上干货(代码)
package com.sqlcreate;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.wb.swt.SWTResourceManager;
import gd.JDBC;
import nide.oi;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
public class CreateSQL {
protected Shell shlsql;
private Text shuchu;
private Text zhanghu;
private Text mima;
private List<String> Databasenames= new ArrayList<>();;
private List<String> Tablenames= new ArrayList<>();
private oi tishi=new oi();
private JDBC yu=new JDBC();
private String []databasenames=new String[] {
};
private String []tablenames=new String[] {
};
private String []fieldnames=new String[] {
};
private String selectDBname="";
private String selectTBname="";
private String selectFieldname="";
private int mysql_version=5;
private Combo comb66=null;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
CreateSQL window = new CreateSQL();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shlsql.open();
shlsql.layout();
while (!shlsql.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shlsql = new Shell();
shlsql.setImage(SWTResourceManager.getImage(CreateSQL.class, "/img/4.png"));
shlsql.setSize(473, 536);
shlsql.setText("MySQL快速生成器");
shuchu = new Text(shlsql, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
shuchu.setBounds(10, 345, 434, 136);
Composite composite = new Composite(shlsql, SWT.BORDER);
composite.setBounds(10, 10, 435, 158);
Label label_2 = new Label(composite, SWT.NONE);
label_2.setImage(SWTResourceManager.getImage(CreateSQL.class, "/img/1.png"));
label_2.setBounds(0, 0, 431, 154);
Composite composite_1 = new Composite(shlsql, SWT.BORDER);
composite_1.setBounds(11, 231, 434, 51);
Combo choose_database = new Combo(composite_1, SWT.NONE);
choose_database.setBounds(118, 10, 92, 28);
choose_database.setText("数据库");
Combo choose_table = new Combo(composite_1, SWT.NONE);
choose_table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
for(int a=0;a<tablenames.length;a++) {
if( choose_table.getSelectionIndex()==a) {
selectTBname=tablenames[a];
System.out.println("目标数据表是:"+selectTBname);
}
}
}
});
choose_table.setBounds(332, 10, 92, 28);
choose_table.setText("数据表");
choose_database.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// 选择数据项:
for(int a=0;a<databasenames.length;a++) {
if( choose_database.getSelectionIndex()==a) {
selectDBname=databasenames[a];
System.out.println("目标数据库是:"+databasenames[a]);
// 然后处理数据表
try {
if(mysql_version==5) {
Tablenames=yu.getAllTableNames(zhanghu.getText(), mima.getText(), selectDBname);
tablenames=new String[Tablenames.size()];
for(int b=0;b<Tablenames.size();b++) {
tablenames[b]=Tablenames.get(b);
}
choose_table.setItems(tablenames);
}else if(mysql_version==8){
Tablenames=yu.getAllTableNames_mysql8(zhanghu.getText(), mima.getText(), selectDBname);
tablenames=new String[Tablenames.size()];
for(int b=0;b<Tablenames.size();b++) {
tablenames[b]=Tablenames.get(b);
}
choose_table.setItems(tablenames);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
});
Label label = new Label(composite_1, SWT.NONE);
label.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 10, SWT.NORMAL));
label.setBounds(10, 11, 102, 23);
label.setText("请选择数据库");
Label label_1 = new Label(composite_1, SWT.NONE);
label_1.setText("请选择数据表");
label_1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 10, SWT.NORMAL));
label_1.setBounds(224, 11, 102, 27);
Composite composite_3 = new Composite(shlsql, SWT.BORDER);
composite_3.setBounds(11, 174, 434, 51);
zhanghu = new Text(composite_3, SWT.BORDER);
zhanghu.setBounds(46, 10, 76, 26);
mima = new Text(composite_3, SWT.BORDER);
mima.setBounds(164, 10, 72, 26);
Label lblNewLabel = new Label(composite_3, SWT.NONE);
lblNewLabel.setBounds(10, 13, 30, 24);
lblNewLabel.setText("账户");
Label lblNewLabel_1 = new Label(composite_3, SWT.NONE);
lblNewLabel_1.setText("密码");
lblNewLabel_1.setBounds(128, 13, 30, 24);
Combo combo = new Combo(composite_3, SWT.NONE);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(combo.getSelectionIndex()==0)
mysql_version=5;
mysql_version=8;
}
});
combo.setItems(new String[] {
"MySQL5.X", "MySQL8.X"});
combo.setBounds(328, 10, 92, 28);
combo.setText("切换版本");
Button lianjie = new Button(composite_3, SWT.NONE);
lianjie.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// 连接数据库的操作
if(zhanghu.getText().equals("")||mima.getText().equals("")) {
tishi.Tishi("404", "请将账户密码输入完整!");
}else if(!zhanghu.getText().equals("")&&!mima.getText().equals("")){
try {
// 首先处理数据库
// 区分数据库版本
if(mysql_version==5) {
yu.GetConnection(zhanghu.getText(), mima.getText());
Databasenames=yu.getDatabasenames(zhanghu.getText(), mima.getText());
// databasenames
String dbnames[]=new String[Databasenames.size()];
for(int a=0;a<Databasenames.size();a++) {
dbnames[a]=Databasenames.get(a);
System.out.println(dbnames[a]);
}
databasenames=dbnames;
System.out.println("转换后:"+Arrays.toString(databasenames));
choose_database.setItems(databasenames);
}else if(mysql_version==8)
{
yu.GetConnection_MySQL_8(zhanghu.getText(), mima.getText());
Databasenames=yu.getDatabasenames_mysql8(zhanghu.getText(), mima.getText());
// databasenames
String dbnames[]=new String[Databasenames.size()];
for(int a=0;a<Databasenames.size();a++) {
dbnames[a]=Databasenames.get(a);
System.out.println(dbnames[a]);
}
databasenames=dbnames;
System.out.println("转换后:"+Arrays.toString(databasenames));
choose_database.setItems(databasenames);
}
} catch (Exception e1) {
System.out.println("第186行代码出错");
e1.printStackTrace();
}
}
}
});
lianjie.setBounds(242, 10, 72, 28);
lianjie.setText("点击连接");
Composite composite_2 = new Composite(shlsql, SWT.BORDER);
composite_2.setBounds(10, 288, 434, 51);
Button insert = new Button(composite_2, SWT.NONE);
insert.setBounds(26, 10, 72, 30);
insert.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String cache = shuchu.getText();
if(!selectDBname.equals("")&&!selectTBname.equals("")) {
List<String> list=null;
try {
if(mysql_version==5) {
list = yu.getColumnNames(zhanghu.getText(),
mima.getText(),selectDBname,selectTBname);
}else if (mysql_version==8) {
list = yu.getColumnNames_mysql8(zhanghu.getText(),
mima.getText(),selectDBname,selectTBname);
}
} catch (Exception E) {
E.printStackTrace();
}
String select = "";
String value="";
for(int a=0;a<list.size();a++) {
if(a==list.size()-1) {
select+=list.get(a);
value+="\""+"\"";
}else {
select+=list.get(a)+",";
value+="\""+"\",";
}
// System.out.println(yu.get(a));
}
// "insert into "+tablename+"("+select+") values("+wenhao+")"
shuchu.setText(cache+"\n"+"插入语句为:"+"insert into "+selectTBname+"("+select+") values("+value+");");
}else {
tishi.Tishi(cache+"\n"+"502","SCX-NULL-POINTER异常错误!当前数据库为:"+selectDBname
+",当前数据表为:"+selectTBname);
}
}
});
insert.setText("插入生成");
Button update = new Button(composite_2, SWT.NONE);
update.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(!selectDBname.equals("")&&!selectTBname.equals("")) {
List<String> list=null;
try {
if(mysql_version==5) {
list = yu.getColumnNames(zhanghu.getText(),
mima.getText(),selectDBname,selectTBname);
}else if (mysql_version==8) {
list = yu.getColumnNames_mysql8(zhanghu.getText(),
mima.getText(),selectDBname,selectTBname);
}
} catch (Exception E) {
E.printStackTrace();
}
String sql="";
for(int a=0;a<list.size();a++) {
if(a==list.size()-1) {
sql+=list.get(a);
sql+="= ' ' ";
}else {
sql+=list.get(a);
sql+="= ' ' ,";
}
// System.out.println(yu.get(a));
}
// "insert into "+tablename+"("+select+") values("+wenhao+")"
String cache = shuchu.getText();
shuchu.setText(cache+"\n"+"感谢您的使用支持!\n更新语句为:\n"+"update "+selectTBname+" set "+sql+" where ' ' = ' '; ");
}else {
tishi.Tishi("502","SCX-NULL-POINTER异常错误!当前数据库为:"+selectDBname
+",当前数据表为:"+selectTBname);
}
}
});
update.setBounds(130, 10, 72, 30);
update.setText("更新生成");
Button select = new Button(composite_2, SWT.NONE);
select.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String cache = shuchu.getText();
if(!selectDBname.equals("")&&!selectTBname.equals("")) {
shuchu.setText(cache+"\n"+"select * from"+selectTBname+"; \n"+"\n显示表结构:\n"+" desc "+selectTBname+";");
}else {
tishi.Tishi(cache+"502","SCX-NULL-POINTER异常错误!当前数据库为:"+selectDBname
+",当前数据表为:"+selectTBname);
}
}
});
select.setBounds(235, 10, 72, 30);
select.setText("查询生成");
Button delete = new Button(composite_2, SWT.NONE);
delete.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String cache = shuchu.getText();
if(!selectDBname.equals("")&&!selectTBname.equals("")) {
shuchu.setText(cache+"\n"+"delete from"+selectTBname+"where ' ' in ' '; \n"+"\n另一种:\n"+" delete from "+
selectTBname+" where ' ' = ' ' ;");
}else {
tishi.Tishi(cache+"502","SCX-NULL-POINTER异常错误!当前数据库为:"+selectDBname
+",当前数据表为:"+selectTBname);
}
}
});
delete.setText("删除生成");
delete.setBounds(334, 10, 72, 30);
}
}
package nide;
import javax.swing.JOptionPane;
public class oi {
// public static void main(String[] args) {
// int res = JOptionPane.showConfirmDialog(null, "阿迪你要先输入全了", "知道了吗", JOptionPane.YES_OPTION);
// if (res == JOptionPane.YES_OPTION) {
// System.out.println("ok"); // 点击“是”后执行这个代码块
// } else {
// System.out.println("略略略");
// }
// }
public void Tishi(String values,String title) {
int res = JOptionPane.showConfirmDialog(null, title, values, JOptionPane.YES_OPTION);
if (res == JOptionPane.YES_OPTION) {
System.out.println("ok"); // 点击“是”后执行这个代码块
} else {
System.out.println("略略略");
}
}
}
最终的演示结果就是这样啦:
如果您觉得本文对您学习基础Java有帮助,加个关注,点个赞支持一下!谢谢啦,嘻嘻