JSP连接MySQL创建数据库,表,字段
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%@page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>创建数据库,表,字段</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<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>
<%!
//连接数据库,取得Statement对象
public Statement getStatement(String url){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(url);
return con.createStatement();
}catch(Exception e){
return null;
}
}
%>
<body>
<%
String sql=null;
String url=null;
Statement st=null;
try{
out.print("<b>创建开始……</b><br>");
sql="CREATE DATABASE task";
url="jdbc:MySQL://localhost:3306?user=root&password=root&characterEncoding=gbk";
st=getStatement(url);//通过指定的url获得Statement对象
st.execute(sql);
out.print("<b>数据库task创建成功……</b><br>");
sql="CREATE TABLE hello(id int(11),name char(20),tel char(50))";
url="jdbc:MySQL://localhost:3306/task?user=root&password=root&characterEncoding=gbk";
st=getStatement(url);//通过指定的url获得Statement对象
st.execute(sql);
out.print("<b>表table创建成功……</b><br>");
out.print("<b>创建结束……</b><br>");
}catch(Exception e){
out.print("<b>创建失败</b>原因:"+e.toString());
}
%>
</body>
</html>