如何使用 JDBC API 在 MySQL 中创建数据库?
A. 通常,您可以使用 CREATE DATABASE 查询创建数据库。
语法
CREATE DATABASE DatabaseName;
要使用 JDBC API 创建数据库,您需要
注册驱动程序:使用 DriverManager 类的 registerDriver() 方法注册驱动程序类。将驱动程序类名作为参数传递给它。
建立连接:使用 DriverManager 类的 getConnection() 方法连接到数据库。将 URL(字符串)、用户名(字符串)、密码(字符串)作为参数传递给它。
创建语句:使用 Connection 接口的 createStatement() 方法创建一个 Statement 对象。
执行查询:使用 Statement 接口的 execute() 方法执行查询。
示例
以下 JDBC 程序建立与 MySQL 的连接并创建一个名为 mydatabase 的数据库
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateDatabaseExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql:///";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to create a database
String query = "CREATE database MyDatabase";
//Executing the query
stmt.execute(query);
System.out.println("Database created");
}
}输出
Connection established...... Database created......
show databases 命令为您提供 MySQL 中数据库的列表。如果您使用此命令验证数据库列表,则可以看到新创建的数据库为
mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | base | | details | | exampledatabase | | logging | | mydatabase | | mydb | | mysql | | performance_schema | | students | | sys | | world | +--------------------+ 12 rows in set (0.00 sec)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP