How to make multiple sql statements from java? -closed

0

[! [] [1]]

This code executes a single sql statement.

public Connection getConnexion(String query){
Connection cnx = null;
try{
Class.forName(driver);
PreparedStatement ps= null;
cnx = (Connection) DriverManager.getConnection(url,usuario,password);
ps = cnx.prepareStatement-(query);
ps.executeUpdate();
ps.close();
System.out.printline("ejecutado correactamente");
}catch(SQLExeption ex){System.out.printline(ex.toString);}
catch(Exeption e){System.out.printline(e.toString);}
return cnx;

}

as you can execute several statements at once. I want to execute multiple statements like this:

query = "créate database base ; use base ; créate table msg(id      char(8),nombre varchar(10),primary key(id)); "

from java [1]

[1]:

    
asked by Ayrton Axel 05.07.2018 в 03:33
source

1 answer

1

Following the principles of the object-oriented programming , you could encapsulate a manager class to take care of the connections and queries, as well as the correct closing of the same. For example:

MySQLManager:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySQLManager {

    private String host;
    private String port;
    private String database;
    private String user;
    private String password;

    public MySQLManager(String host, String port, String database, String user, String password) {
        this.host = host;
        this.port = port;
        this.database = database;
        this.user = user;
        this.password = password;
    }

    private Connection createConnection() {
        Connection connection;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user,
                    password);
            return connection;
        } catch (SQLException e) {
            System.out.println("Could not connect to MySQL server! because: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            System.out.println("JDBC Driver not found!");
        }
        return null;
    }

    public ResultSet executeQuery(String query) {
        Connection connection = createConnection();
        Statement statement = null;
        ResultSet set = null;
        try {
            statement = connection.createStatement();
            set = statement.executeQuery(query);
            return set;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally { // Close in order: ResultSet, Statement, Connection.
            try {
                set.close();
            } catch (Exception e) {
            }
            try {
                statement.close();
            } catch (Exception e) {
            }
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    public void executeUpdate(String update) {
        Connection connection = createConnection();
        Statement statement = null;
        try {
            statement = connection.createStatement();
            statement.executeUpdate(update);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (Exception e) {
            }
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}

Connection Test:

Finally, you can take charge of carrying out your actions only by entering the correct parameters and let the class take care of the rest.

import java.sql.ResultSet;

public class PruebaConexion {

    public static void main(String[] args) {
        MySQLManager manager = new MySQLManager("localhost", "3306", "mydatabase", "user", "pass");
        manager.executeUpdate("create database if not exists base");
        manager.executeUpdate("use base");
        manager.executeUpdate("create table if not exists msg (id int primary key auto_increment, nombre varchar(45))");
        //crear n tablas...

        //Queries
        String sql = "select * from msg";
        ResultSet rs = manager.executeQuery(sql);
    }

}

As an extra, if you want to take action with your results, I'll give you an example:

while (result.next()) {

    Product product = new Product();

    product.setTotal(result.getDouble("Total"));
    product.setName(result.getString("Name"));
    // etc.

    productList.add(product);
}

The recipe is the same, you just have to adapt it to your problem.

MultipleQueries:

Ignoring all of the above, you can modify the AllowMultipleQueries parameter to allow queries separated by commas. Fitting a small example, testing on my computer, you could implement something like this:

import java.sql.*;
import java.util.*;


public class MultipleQueriesTest {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306";
        String userName = "root";
        String password = "pass";
        Properties props =  new Properties();
        props.put("user",userName);
        props.put("password",password);
        props.put("allowMultiQueries","true");
        Connection conn = null;

        Class.forName(driver);
        conn=DriverManager.getConnection(url,props);            

        Statement stmt = conn.createStatement();

        stmt.executeUpdate( "CREATE DATABASE IF NOT EXISTS facturacion; USE facturacion;DROP TABLE IF EXISTS tclientes; CREATE TABLE tclientes ( idcliente VARCHAR(10) NOT NULL DEFAULT '', nombre VARCHAR(50) NULL DEFAULT NULL, PRIMARY KEY (idcliente) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB" );

        System.out.println("Tabla tclientes creada existosamente");



    }

}

Output:

Tabla tclientes creada existosamente

Existence Verification:

    
answered by 05.07.2018 / 08:48
source