java数据库学生信息表,带注释
时间: 2023-10-17 12:24:16 浏览: 90
下面是一个简单的Java程序,用于创建一个学生信息表,并将其存储在数据库中。程序使用了JDBC API来连接和操作数据库。
```java
import java.sql.*; //导入java.sql包
public class StudentTable {
public static void main(String[] args) {
Connection conn = null; //定义Connection对象
Statement stmt = null; //定义Statement对象
try{
//注册JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
//打开连接
System.out.println("连接数据库...");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","password");
//执行查询
System.out.println("创建学生信息表...");
stmt = conn.createStatement();
//创建学生信息表
String sql = "CREATE TABLE Student " +
"(id INT(11) NOT NULL AUTO_INCREMENT, " +
" name VARCHAR(255), " +
" age INT(11), " +
" PRIMARY KEY ( id ))";
//执行SQL语句
stmt.executeUpdate(sql);
System.out.println("学生信息表创建成功!");
//关闭连接
stmt.close();
conn.close();
}catch(SQLException se){
//处理JDBC异常
se.printStackTrace();
}catch(Exception e){
//处理Class.forName异常
e.printStackTrace();
}finally{
//关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
程序中使用了JDBC API来连接和操作MySQL数据库。首先,我们需要注册JDBC驱动,通过调用Class.forName("com.mysql.jdbc.Driver")方法实现。然后,我们通过DriverManager.getConnection方法打开一个数据库连接。在连接成功后,我们可以使用Statement对象来执行SQL语句。在这个程序中,我们创建了一个名为Student的表,并定义了三个列:id、name和age。最后,我们关闭了Statement和Connection对象,关闭了数据库连接。
需要注意的是,这个程序只是一个示例程序,实际应用中可能需要更复杂的操作。例如,我们可能需要添加更多的列,或者使用PreparedStatement来执行更复杂的SQL语句。
阅读全文
相关推荐


















