从java在mysql中创建一个数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19009117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:20:09  来源:igfitidea点击:

creating a database in mysql from java

javamysqldatabasejdbc

提问by K Spriggs

Could you help with this problem.

你能帮忙解决这个问题吗。

I'm trying to create and then use a database called TIGER.

我正在尝试创建然后使用名为 TIGER 的数据库。

I have no problem if I create the database in MySQL and it runs perfectly.

如果我在 MySQL 中创建数据库并且它运行完美,我没有问题。

What I would like to do is create it from Java. So that when the code is being run for the first time it creates the database as part of the initial launch. I would like to box it up in a nice clean method if possible.

我想做的是从 Java 创建它。因此,当第一次运行代码时,它会创建数据库作为初始启动的一部分。如果可能的话,我想用一种干净的方法把它装箱。

Could it be possible for someone to show me where you actually position the code

有人可以告诉我您实际放置代码的位置吗

Here is the code

这是代码

    private String jdbcDriver = "com.mysql.jdbc.Driver";
    private String dbAddress = "jdbc:mysql://localhost:3306/";
    private String dbName = "TIGER";
    private String userName = "root";
    private String password = "";

    private PreparedStatement statement;
    private ResultSet result;
    private Connection con;

    public DbStuff() {
        try {
            Class.forName(jdbcDriver);
            con = DriverManager.getConnection(dbAddress + dbName, userName, password);
        } 

        catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

and here is the code to create the database

这是创建数据库的代码

    con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
    statement = Conn.createStatement();
    int myResult = statement.executeUpdate("CREATE DATABASE TIGER");

Thanks in advance and any and all help is appreciated

提前致谢,感谢任何和所有帮助

Sorry for the mistakes as I'm a long term reader but a new writer.

对不起,我是一个长期读者但一个新作家的错误。

When I try do run the main part of the code it generates an SQLException because the database doesn't exist. At this point I would like to catch the exception and create the database at that point. But when I try this it doesn't create the database.

当我尝试运行代码的主要部分时,它会生成一个 SQLException,因为数据库不存在。此时我想捕获异常并在那时创建数据库。但是当我尝试这个时它不会创建数据库。

采纳答案by Masudul

Try with this code.

尝试使用此代码。

public class DbStuff {

    private static String jdbcDriver = "com.mysql.jdbc.Driver";
    private static String dbName = "TIGER";


    public static void main(String[] args) throws Exception {
        Class.forName(jdbcDriver);
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=");
        Statement s = conn.createStatement();
        int Result = s.executeUpdate("CREATE DATABASE "+dbName);
    }
}

回答by lpdavis13

You could always run

你总是可以跑

int myResult = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS TIGER;")

If this is ran on project start up it will simply check if the database exists and if it doesn't it will create the new database.

如果这是在项目启动时运行,它只会检查数据库是否存在,如果不存在,它将创建新数据库。

For reference: http://dev.mysql.com/doc/refman/5.0/en/create-database.html

供参考:http: //dev.mysql.com/doc/refman/5.0/en/create-database.html

回答by user2810910

On an unrelated (to the question) note:

关于(与问题)无关的注释:

I don't think it's ever a good idea to programmatically generate the database. You will be better off using the utility tool that comes with your database. Everyone that works with MySQL will almost certainly be familiar with the utility tool and will not have to become familiar with your Java code, change it, compile it, and run it to make a change. Also, the utility has a rich set of features that your Java code probably doesn't have such as assigning permissions, indexing, setting up foreign keys, etc.

我认为以编程方式生成数据库不是一个好主意。最好使用数据库附带的实用工具。使用 MySQL 的每个人几乎肯定都熟悉实用工具,并且不必熟悉 Java 代码、更改它、编译它并运行它来进行更改。此外,该实用程序具有一组丰富的功能,您的 Java 代码可能没有这些功能,例如分配权限、索引、设置外键等。

回答by K Spriggs

First of all,

首先,

I would like to thank all those who answered it was very helpful indeed to get different views and opinions.

我要感谢所有回答它的人,这对于获得不同的观点和意见确实非常有帮助。

Here is the solution that I have together.

这是我一起拥有的解决方案。

    public class DbStuff {
    private String jdbcDriver = "com.mysql.jdbc.Driver";
    private String dbAddress = "jdbc:mysql://localhost:3306/";
    private String userPass = "?user=root&password=";
    private String dbName = "TIGER";
    private String userName = "root";
    private String password = "";

    private PreparedStatement statement;
    private ResultSet result;
    private Connection con;

    public DbStuff() {

        try {
            Class.forName(jdbcDriver);
            con = DriverManager.getConnection(dbAddress + dbName, userName, password);
        } 

        catch (ClassNotFoundException e) {
            e.printStackTrace();
        } 
        catch (SQLException e) {
            createDatabase();
        }
    }

    private void createDatabase() {
        try {
        Class.forName(jdbcDriver);
        con = DriverManager.getConnection(dbAddress + userPass);
        Statement s = con.createStatement();
        int myResult = s.executeUpdate("CREATE DATABASE " + dbName);
        } 
        catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }

Feel free to comment on any of the code. I know using the e.printStackTrace() is not the best way forward, don't worry It will be modified later on.

随意评论任何代码。我知道使用 e.printStackTrace() 不是最好的方法,别担心,以后会修改。

回答by Aniket Thakur

Few points to note and correct-

有几点需要注意和纠正——

  1. You have declared Connection Object as private Connection con;but you are using it as statement = Conn.createStatement();
  2. You have declared a reference to Prepared Statement private PreparedStatement statement;but you are creating instance of Statement statement = Conn.createStatement();. Your code should be -

    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
        Statement  statement = con.createStatement();
        int myResult = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS TIGER"); //should get 0
    }
    catch (SQLException e) {
        System.out.println("Database creation failed");
        e.printStackTrace();
    } 
    
  1. 您已将连接对象声明为,private Connection con;但您将其用作statement = Conn.createStatement();
  2. 您已经声明了对 Prepared Statement 的引用,private PreparedStatement statement;但您正在创建 Statement 的实例statement = Conn.createStatement();。你的代码应该是 -

    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
        Statement  statement = con.createStatement();
        int myResult = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS TIGER"); //should get 0
    }
    catch (SQLException e) {
        System.out.println("Database creation failed");
        e.printStackTrace();
    } 
    

Note that when the return value for executeUpdate is 0, it can mean one of two things:

请注意,当 executeUpdate 的返回值为 0 时,它可能意味着以下两种情况之一:

  • The statement executed was an update statement that affected zero rows.

  • The statement executed was a DDL statement.

  • 执行的语句是影响零行的更新语句。

  • 执行的语句是 DDL 语句。

Documentation

文档

回答by Gurkamal singh

The easy approach to problem is :

解决问题的简单方法是:

package Database;
import java.sql.*;

public class Database {

 public static void main(String[] args) {
    final  String URl = "JDBC:mysql:/localhost:3306/info";
    final  String id = "root";
    final  String  password = "";

    try
    {
        Connection con1 = DriverManager.getConnection(URl,id,password);
        Statement s1 = con1.createStatement();
        String s = "CREATE DATABASE CLASSIFIED";
        s1.executeUpdate(s);

    }
    catch(SQLException err)
    {
        System.out.println(err.getMessage());
    }

 }

}

回答by Zaknafein

I suggest to use this snippet of code

我建议使用这段代码

private String jdbcDriver = "com.mysql.jdbc.Driver";
private String dbAddress = "jdbc:mysql://localhost:3306/TIGER?createDatabaseIfNotExist=true";
private String userName = "root";
private String password = "";

private PreparedStatement statement;
private ResultSet result;
private Connection con;

public DbStuff() {
    try {
        Class.forName(jdbcDriver);
        con = DriverManager.getConnection(dbAddress, userName, password);
    } 

    catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}