用java新建数据库mis,建立学生表tstudent
时间: 2024-02-09 16:10:43 浏览: 96
好的,以下是用Java代码新建数据库mis,并建立学生表tstudent的示例代码,需要先确保已经安装并配置好了Java的数据库连接驱动程序:
```java
import java.sql.*;
public class CreateDatabaseAndTable {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String db = "mis";
String user = "root";
String password = "root";
Connection conn = null;
Statement stmt = null;
try {
// 加载数据库连接驱动
Class.forName(driver);
// 创建数据库连接
conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
stmt = conn.createStatement();
// 创建mis数据库
String sqlCreateDB = "CREATE DATABASE IF NOT EXISTS " + db;
stmt.executeUpdate(sqlCreateDB);
// 切换到mis数据库
stmt.execute("USE " + db);
// 创建tstudent表
String sqlCreateTable = "CREATE TABLE IF NOT EXISTS tstudent ("
+ "id INT PRIMARY KEY AUTO_INCREMENT,"
+ "name VARCHAR(20) NOT NULL,"
+ "gender VARCHAR(2) NOT NULL,"
+ "age INT NOT NULL,"
+ "department VARCHAR(20) NOT NULL,"
+ "major VARCHAR(20) NOT NULL,"
+ "grade INT NOT NULL"
+ ")";
stmt.executeUpdate(sqlCreateTable);
// 输出成功信息
System.out.println("Database mis and table tstudent created successfully!");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
// 关闭Statement对象
if (stmt != null) stmt.close();
// 关闭数据库连接
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
以上Java代码中,我们使用了Java标准库中的JDBC API来连接MySQL数据库,并执行了创建数据库、创建表的操作。在运行该Java程序之前,请确保已经安装并配置好了MySQL数据库,并将MySQL的JDBC连接驱动程序放置在classpath路径下。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)