Java项目生成电脑桌面快捷脚本(Mysql数据)
一、场景说明
在项目中,可能有些同事需要查询线上数据库的数据,但又不能泄露密码给他们,手写一个程序方便他们查询。
需要引入mysql驱动包:downloads.mysql.com
// mysql8.0以上版本com.mysql.jdbc.Driver 更换为 com.mysql.cj.jdbc.Driver
private static final String driver = "com.mysql.jdbc.Driver";
private static final String con_url = "jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8";
private static final String user_name = "root";
private static final String user_passward = "forlan";
// 驱动只需要加载一次,所以放在静态代码块里面
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ResultSet rs = null;
try (Connection connection = DriverManager.getConnection(con_url, user_name, user_passward);
Statement stmt = connection.createStatement(); Scanner sc = new Scanner(System.in)) {
while (true) {
System.out.println("请输入要执行的sql:");
String sql = sc.nextLine();
StringBuilder sb = new StringBuilder();
rs = stmt.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
for (int i = 0; i < metaData.getColumnCount(); i++) {
String col_name = metaData.getColumnName(i + 1);// 获取列名
sb.append(col_name).append("=").append(rs.getObject(col_name)).append(";");
}
sb.append("\n");
}
System.out.println(sb.toString());
}
} catch (Exception e) {
System.out.println("执行失败,请联系管理员处理");
e.printStackTrace();
}finally {
try {
rs.close