直接从java创建数据库和表

new9mtju  于 2021-06-27  发布在  Java
关注(0)|答案(0)|浏览(181)

我尝试直接从java创建表,而不是使用phpmyadmin创建它们。代码看起来运行得很顺利,但当查询到达时,它会给出某种错误,我正在尝试识别,但我无法识别。下面是我一直在尝试的代码:

package filmoteca;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class GestionBDD {
    private static String datosConexion = "jdbc:mysql://127.0.0.1:3306/";
    private static String baseDatos = "cine";
    private static String usuario = "root";
    private static String pass = "";
        private static String tabla = "pelicula";
    private Connection con;

    public GestionBDD() {
        try {
            con = DriverManager.getConnection(datosConexion, usuario, pass);
                        try{
                            crearBDD();
                            crearTablas();
                        }catch(Exception e){
                            e.printStackTrace();
                        }
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }

        public void crearBDD() throws Exception{
            String query = "CREATE DATABASE IF NOT EXISTS"+ baseDatos +";";
            Statement stat = null;

            try{
                stat = con.createStatement();
                stat.executeUpdate(query);
                con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);
            }catch(SQLException e){
                e.printStackTrace();
            }finally{
                stat.close();
            }
        }

        public void crearTablas() throws Exception{
            String query = "USE DATABASE "+baseDatos+";"+
                    "CREATE TABLE IF NOT EXISTS"+" "+tabla+"("
                    + "titulo VARCHAR(30), "
                    + "director VARCHAR(30), "
                    + "pais VARCHAR(30), "
                    + "duracion FLOAT, "
                    + "genero VARCHAR(30));";
            Statement stat = null;
            try{
               stat = con.createStatement();
               stat.executeUpdate(query);
               con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);

            }catch(SQLException e){
                e.printStackTrace();
            }finally{
                stat.close();
            }
        }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题