Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.InputStreamReader;
- import java.sql.*;
- import java.util.LinkedList;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.util.Scanner;
- public class Diagnostico {
- private final String DATAFILE = "data/disease_data.data";
- private Connection conn = null;
- private String nombreBD = "diagnostico";
- private class Codigo {
- private String vocabulario;
- private String codigo;
- public Codigo(String codigo,String vocabulario) {
- this.vocabulario = vocabulario;
- this.codigo = codigo;
- }
- public String getVocabulario() {
- return vocabulario;
- }
- public String getCodigo() {
- return codigo;
- }
- }//class codigo
- private class Sintoma {
- private String codigoSintoma;
- private String semanticaTipo;
- private String sintoma;
- public Sintoma(String sintoma,String codigoSintoma,String semanticaTipo) {
- this.codigoSintoma = codigoSintoma;
- this.semanticaTipo = semanticaTipo;
- this.sintoma = sintoma;
- }
- public String getCodigoSintoma() {
- return codigoSintoma;
- }
- public String getSemanticaTipo() {
- return semanticaTipo;
- }
- public String getSintoma() {
- return sintoma;
- }
- }//class sintoma
- private class Enfermedad {
- private LinkedList<Codigo> codigo;
- private LinkedList<Sintoma> sintoma;
- private String nombre;
- public Enfermedad (String nombre,LinkedList<Codigo> codigo,LinkedList<Sintoma>sintoma) {
- this.nombre= nombre;
- this.codigo = codigo;
- this.sintoma = sintoma;
- }
- public String getNombre() {
- return nombre;
- }
- public LinkedList<Codigo> getCodigo() {
- return codigo ;
- }
- public LinkedList<Sintoma> getSintoma() {
- return sintoma;
- }
- }
- private void showMenu() {
- int option = -1;
- do {
- System.out.println("Bienvenido a sistema de diagnóstico\n");
- System.out.println("Selecciona una opción:\n");
- System.out.println("\t1. Creación de base de datos y carga de datos.");
- System.out.println("\t2. Realizar diagnóstico.");
- System.out.println("\t3. Listar síntomas de una enfermedad.");
- System.out.println("\t4. Listar enfermedades y sus códigos asociados.");
- System.out.println("\t5. Listar síntomas existentes en la BD y su tipo semántico.");
- System.out.println("\t6. Mostrar estadísticas de la base de datos.");
- System.out.println("\t7. Salir.");
- try {
- option = readInt();
- switch (option) {
- case 1:
- crearBD();
- break;
- case 2:
- realizarDiagnostico();
- break;
- case 3:
- listarSintomasEnfermedad();
- break;
- case 4:
- listarEnfermedadesYCodigosAsociados();
- break;
- case 5:
- listarSintomasYTiposSemanticos();
- break;
- case 6:
- mostrarEstadisticasBD();
- break;
- case 7:
- exit();
- break;
- }
- } catch (Exception e) {
- System.err.println("Opción introducida no válida!");
- }
- } while (option != 7);
- exit();
- }
- private void exit() {
- if (conn != null){
- try{
- if(!conn.isClosed())
- conn.close();
- }
- catch (Exception e){
- System.out.println("No se pudo desconectar de la base de datos");
- }
- }
- System.out.println("Saliendo.. ¡hasta otra!");
- System.exit(0);
- }
- private boolean existeDB() {
- boolean exist = false;
- try{
- Statement st = conn.createStatement();
- String sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + this.nombreBD + "'";
- ResultSet rs = st.executeQuery(sql);
- if (rs.next()) {
- exist = true;
- }
- }catch (SQLException ex) {
- exist = false;
- } return exist;
- }
- private void conectar() throws Exception {
- String drv ="com.mysql.jdbc.Driver";
- Class.forName(drv).newInstance();
- String serverAddress = "localhost:3306";
- String user = "bddx";
- String pwd = "bddx_pwd";
- String url = "jdbc:mysql://" + serverAddress + "/";
- conn = DriverManager.getConnection(url, user, pwd);
- if (!conn.isClosed()){
- System.out.println("¡Conectado a la base de datos!");
- }
- }
- private void crearBD() {
- try{
- if(conn == null){
- this.conectar();
- }
- }
- catch(Exception e) {
- System.out.println(e);
- }
- try{
- if(!existeDB()){
- Statement stmt = conn.createStatement();
- System.out.println("Creando diagnostico...");
- String qs= "CREATE DATABASE diagnostico";
- stmt.executeUpdate(qs);
- conn.setCatalog(nombreBD);
- System.out.println("La base de datos diagnostico ha sido creada.");
- Statement stmt1= conn.createStatement();
- stmt1.executeUpdate("CREATE TABLE source (source_id INT UNIQUE AUTO_INCREMENT, name VARCHAR(255))");
- Statement stmt2= conn.createStatement();
- stmt2.executeUpdate("CREATE TABLE code (source_id INT, code VARCHAR(255), PRIMARY KEY (code), FOREIGN KEY (source_id)"
- + " REFERENCES source (source_id))");
- Statement stmt3= conn.createStatement();
- stmt3.executeUpdate("CREATE TABLE disease (disease_id INT UNIQUE AUTO_INCREMENT, name VARCHAR(255))");
- Statement stmt4= conn.createStatement();
- stmt4.executeUpdate("CREATE TABLE disease_has_code (source_id INT, code VARCHAR(255),disease_id INT, FOREIGN KEY (disease_id)"
- + " REFERENCES disease (disease_id), FOREIGN KEY (code) REFERENCES code (code), FOREIGN KEY (source_id) "
- + "REFERENCES code (source_id))");
- Statement stmt6= conn.createStatement();
- stmt6.executeUpdate("CREATE TABLE semantic_type (semantic_type_id INT UNIQUE AUTO_INCREMENT, cui VARCHAR(45))");
- Statement stmt5= conn.createStatement();
- stmt5.executeUpdate("CREATE TABLE symptom (cui VARCHAR(25), name VARCHAR(255), semantic_type_id INT, PRIMARY KEY (cui),"
- + " FOREIGN KEY (semantic_type_id) REFERENCES semantic_type (semantic_type_id))");
- Statement stmt7= conn.createStatement();
- stmt7.executeUpdate("CREATE TABLE disease_symptom (disease_id INT, cui VARCHAR(25), FOREIGN KEY (disease_id) REFERENCES disease (disease_id),"
- + " FOREIGN KEY (cui) REFERENCES symptom (cui))");
- LinkedList<String> lista = readData();
- for(String enfermedades: lista){
- String arreglado = enfermedades.replaceAll("'", "''"); //cambiamos los apostrofes por doble apostrofe para que no haya problemas al insertar
- String [] cadena= arreglado.split("="); // separamos enfermedad[0] y sintomas[1]
- String [] cadEnf = cadena[0].split(":"); // separamos enfermedad[0] de codigo y vocabulario[1]
- String nomEnf= cadEnf[0];
- String [] cadCodigos= cadEnf[1].split(";"); //separamos los codigos
- LinkedList<Codigo> lisCod = new LinkedList<>();
- for(int i=0;i<cadCodigos.length; i++){
- String [] codigo= cadCodigos[i].split("@"); // separamos codigo[0] y vocabulario[1]
- String cod= codigo[0]; //di si a los comentarios!
- String voc= codigo[1];
- Codigo cd= new Codigo (cod,voc); //creamos un nuevo codigo ( codigo, vocabulario)
- lisCod.add(cd);
- }
- String [] cadSint= cadena[1].split(";"); //separamos los sintomas
- LinkedList<Sintoma> lisSint = new LinkedList<>();
- for(int i=0; i<cadSint.length; i++){
- String [] sintomas= cadSint[i].split(":"); //separamos sintoma, codigoSintoma y vocabularioSint
- String sint=sintomas[0];
- String codSint= sintomas[1];
- String vocSint= sintomas[2];
- Sintoma st= new Sintoma (sint, codSint, vocSint); // creamos nuevo Sintoma(sintoma, codigoSintoma, vocabulario)
- lisSint.add(st);
- }
- Enfermedad enfermito = new Enfermedad(nomEnf,lisCod,lisSint);
- conn.setAutoCommit(false);
- //insercion datos Tabla SOURCE
- String sqlSou= "INSERT INTO source (name) VALUES ('"+enfermito.getCodigo().element().getVocabulario()+"')";
- stmt1.executeUpdate(sqlSou,Statement.RETURN_GENERATED_KEYS);
- ResultSet souKey = stmt1.getGeneratedKeys();
- souKey.next();
- //insercion datos Tabla CODE
- stmt2.executeUpdate("INSERT INTO code (source_id, code) VALUES ('"+souKey.getInt(1)+"','"+enfermito.getCodigo().element().getCodigo()+"')");
- ResultSet codeKey = stmt2.executeQuery("SELECT code FROM code");
- codeKey.next();
- //insercion datos Tabla DISEASE
- System.out.println(enfermito.getNombre().toString());
- // String prueba = enfermito.getNombre().replaceAll("'","''");
- String sqlDis= "INSERT INTO disease (name) VALUES ('"+enfermito.getNombre()+"')"; //esta es la que provoca el error y ni idea de porque
- stmt3.executeUpdate(sqlDis, Statement.RETURN_GENERATED_KEYS);
- ResultSet disKey = stmt3.getGeneratedKeys();
- disKey.next();
- //insercion datos Tabla DISEASE_HAS_CODE
- stmt4.executeUpdate("INSERT INTO disease_has_code (source_id, code,disease_id) VALUES ('"+souKey.getInt(1)+"','"+codeKey.getString(1)+""
- + "','"+disKey.getInt(1)+"')");
- //insercion datos Tabla semantic_type
- String sqlSem= "INSERT INTO semantic_type(cui) VALUES ('"+enfermito.getSintoma().element().getSemanticaTipo()+"')";
- stmt6.executeUpdate(sqlSem, Statement.RETURN_GENERATED_KEYS);
- ResultSet semKey = stmt6.getGeneratedKeys();
- semKey.next();
- //insercion datos Tabla symptom
- stmt5.executeUpdate("INSERT INTO symptom (cui,name,semantic_type_id) VALUES ('"+enfermito.getSintoma().element().getCodigoSintoma()+"',"
- + "'"+enfermito.getSintoma().element().getSintoma()+"','"+semKey.getInt(1)+"')");
- ResultSet sympKey = stmt2.executeQuery("SELECT cui FROM symptom");
- sympKey.next();
- //insercion datos Tabla disease_symptom
- stmt7.executeUpdate("INSERT INTO disease_symptom (disease_id, cui) VALUES ('"+disKey.getInt(1)+"','"+sympKey.getString(1)+"')");
- souKey.close();
- codeKey.close();
- disKey.close();
- semKey.close();
- sympKey.close();
- }//fin insertar
- //Ahora procedemos a cerrar los Statement
- stmt1.close();
- stmt2.close();
- stmt3.close();
- stmt4.close();
- stmt5.close();
- stmt6.close();
- stmt7.close();
- }
- else{
- Scanner scanner = new Scanner(System.in);
- System.out.println("Le informamos de la existencia de diagnostico, ¿desea borrarla?");
- String condicion = scanner.nextLine();
- if(condicion.equals("Si")|| condicion.equals("si")){
- Statement stmt = conn.createStatement();
- System.out.println("Borrando diagnostico...");
- String qs= "DROP DATABASE diagnostico";
- stmt.executeUpdate(qs);
- System.out.println("Borrado completado.");
- System.out.println("Creando la base de datos de nuevo.");
- stmt.close();
- this.crearBD();
- }
- }//fin existeBD
- conn.commit();
- }//fin try
- catch (Exception e) {
- try {
- conn.rollback();
- } catch (SQLException e1) {
- System.out.println(e);
- }
- System.out.println(e);
- }//fin catch
- finally{
- try {
- conn.setAutoCommit(true);
- } catch (SQLException e) {
- System.out.println(e);
- }
- }//fin finally
- //
- // String base = "CREATE SCHEMA if not exists diagnostico;";
- // String source = "CREATE TABLE diagnostico."
- // + "source (source_id INT NULL,"
- // + " name VARCHAR(255) NULL,PRIMARY KEY (source_id));";
- // String code = "CREATE TABLE diagnostico."
- // + "code (code VARCHAR(255) NOT NULL, "
- // + "source_id INT NULL,PRIMARY KEY (code));";
- // String disease_has_code = "";
- // String disease = "";
- // String disease_symptom = "";
- // String symptom = "";
- // String symptom_semantic_type = "";
- // String semantic_type = "";
- // try{
- // if (conn == null || conn.isClosed())
- // this.conectar();
- // }
- // catch(Exception e){
- //
- // }
- // Statement st = conn.createStatement();
- // // Comprobamos si existe la base de datos
- // ResultSet rs = st.executeQuery("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'diagnostico' ");
- // // Si no existe la creamos
- // if(rs == null || !rs.next()){
- // st.executeUpdate(base);
- // }
- // else {
- // //Preguntamos si se quiere borrar la base
- // Scanner sc = new Scanner(System.in);
- // System.out.println("¿Quieres borrar la base de datos? S/N");
- // String respuesta = sc.next();
- // sc.close();
- // // Se crea de nuevo
- // if (respuesta.equals("S")){
- // st.executeUpdate("DROP DATABASE diagnostico;");
- // this.crearBD();
- // }
- // }
- }
- private void realizarDiagnostico() {
- try {
- if (conn == null || conn.isClosed())
- this.conectar();
- }
- catch (Exception e) {
- System.out.println(e);
- }
- /* Lo que tenga que hacer */
- }
- private void listarSintomasEnfermedad() {
- try {
- if (conn == null || conn.isClosed())
- this.conectar();
- }
- catch (Exception e) {
- System.out.println(e);
- }
- /* Lo que tenga que hacer */
- }
- private void listarEnfermedadesYCodigosAsociados() {
- try {
- if (conn == null || conn.isClosed())
- this.conectar();
- }
- catch (Exception e) {
- System.out.println(e);
- }
- /* Lo que tenga que hacer */
- }
- private void listarSintomasYTiposSemanticos() {
- try {
- if (conn == null || conn.isClosed())
- this.conectar();
- }
- catch (Exception e) {
- System.out.println(e);
- }
- /* Lo que tenga que hacer */
- }
- private void mostrarEstadisticasBD() {
- try {
- if (conn == null || conn.isClosed())
- this.conectar();
- }
- catch (Exception e) {
- System.out.println(e);
- }
- /* Lo que tenga que hacer */
- }
- /**
- * Método para leer números enteros de teclado.
- *
- * @return Devuelve el número leído.
- * @throws Exception
- * Puede lanzar excepción.
- */
- private int readInt() throws Exception {
- try {
- System.out.print("> ");
- return Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
- } catch (Exception e) {
- throw new Exception("Not number");
- }
- }
- /**
- * Método para leer cadenas de teclado.
- *
- * @return Devuelve la cadena leída.
- * @throws Exception
- * Puede lanzar excepción.
- */
- private String readString() throws Exception {
- try {
- System.out.print("> ");
- return new BufferedReader(new InputStreamReader(System.in)).readLine();
- } catch (Exception e) {
- throw new Exception("Error reading line");
- }
- }
- /**
- * Método para leer el fichero que contiene los datos.
- *
- * @return Devuelve una lista de String con el contenido.
- * @throws Exception
- * Puede lanzar excepción.
- */
- private LinkedList<String> readData() throws Exception {
- LinkedList<String> data = new LinkedList<String>();
- BufferedReader bL = new BufferedReader(new FileReader(DATAFILE));
- while (bL.ready()) {
- data.add(bL.readLine());
- }
- bL.close();
- return data;
- }
- public static void main(String args[]) throws Exception {
- new Diagnostico().showMenu();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement