Myecilpse web +tomcat 项目: JSP在mysql中创建表

时间:2025-04-17 22:33:37
<%@ page language="java" import="java.util.*" import="com.mysql.jdbc.Driver" import="java.sql.*" contentType="text/html;charset=gb2312" pageEncoding="UTF-8"%>
<!--导入相关的类 ,规定编码gb2312-->
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'creatStuTable.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
This is my JSP page. <br>
<%
Connection conn;
Statement stat;
//取得连接的url
String url="jdbc:mysql://localhost:3306/student";
//使用用户名root,因为在创建数据库时没有指定数据库的用户名,故使用安装mysql配置的root,密码也是安装时我配置的zhangweijie.
String userName="root";
String password="zhangweijie";
try{
//注册JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException ex)
{
out.println("找不到驱动程序!");
}
//打开数据库连接
conn=DriverManager.getConnection(url,userName,password);
try{
stat=conn.createStatement();
//如果存在同名的数据表,先进行删除
stat.executeUpdate("drop table if exists Student_Info;");
//执行创建表的SQL语句
stat.executeUpdate("create table Student_Info (StuID int not null auto_increment,StuName varchar(50) not null,Telephone varchar(20) not null,primary key(StuID));");
//打印提示结果
out.println("数据表Student_Info创建成功");
} catch(SQLException ex)
{ out.println("数据表Student_Info创建失败");
} finally{
//关闭数据库连接
conn.close();
}
%>
</body>
</html>