Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.quanlytoanha.autowritesql;
- import java.sql.*;
- public class AutoWriteSQL {
- public Connection getConnection() {
- try {
- Class.forName("com.mysql.cj.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/quanlytoanha";
- String user = "root";
- String password = "123";
- return DriverManager.getConnection(url, user, password);
- } catch (ClassNotFoundException | SQLException e) {
- return null;
- }
- }
- public void autoWriteUpdateSQL() {
- Connection connection = getConnection();
- try {
- PreparedStatement statement = connection.prepareStatement("select *from user");
- ResultSet rs = statement.executeQuery();
- ResultSetMetaData rsmd = rs.getMetaData();
- int count = rsmd.getColumnCount();
- StringBuilder sql = new StringBuilder("update " + rsmd.getTableName(1) +" set ");
- for (int i = 2 ; i <=count ; i++) {
- if(i==count){
- sql.append(rsmd.getColumnName(i) + " = ? " );
- } else {
- sql.append(rsmd.getColumnName(i) + " = ? , " );
- }
- }
- sql.append(" where id = ? ");
- System.out.println(sql.toString());
- }catch (SQLException e){
- System.out.println(e.getMessage());
- }
- }
- public void autoWriteInsertSQL() {
- Connection connection = getConnection();
- try {
- PreparedStatement statement = connection.prepareStatement("select *from user");
- ResultSet rs = statement.executeQuery();
- ResultSetMetaData rsmd = rs.getMetaData();
- int count = rsmd.getColumnCount();
- StringBuilder sql = new StringBuilder("insert into " + rsmd.getTableName(1) +" ( ");
- for (int i = 2 ; i <=count ; i++) {
- if (rsmd.getColumnName(i).equals("modifieddate")) {
- continue;
- }
- if (rsmd.getColumnName(i).equals("modifiedby")) {
- sql.delete(sql.length()-2 , sql.length());
- sql.append(" )");
- break;
- }
- sql.append(rsmd.getColumnName(i) + " , " );
- }
- sql.append(" values( ");
- for (int i = 2 ; i <=count-2 ; i++) {
- if(i==count-2){
- sql.append("? ) ");
- } else {
- sql.append("?, ");
- }
- }
- System.out.println(sql.toString());
- }catch (SQLException e){
- System.out.println(e.getMessage());
- }
- }
- public static void main(String[] args) {
- autoWriteInsertSQL();
- autoWriteUpdateSQL()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement