jsp怎么连接mysql(jsp怎么连接mysql数据库)-编程之家

如何用

jsp连接mysql数据库

一、软件环境

下载并安装MySQL、Tomacat、JDBC、MyEclipse或其他ide。

二、环境配置

配置完环境变量后,下载连接到MySQL的特定于Java的驱动包JDBC。有些人会在一些下载的JDBC压缩包里找到一些文件,比如MySQL-connector-Java-GPL-5 . 1 . 34 . MSI的安装文件,这个文件是干什么用的,和MySQL-connector-Java-5 . 1 . 34-bin . jar有什么关系?其实两者是一样的,只是MySQL-connector-Java-GPL-5 . 1 . 34 . msi在里面封装了MySQL-connector-Java-5.1 . xx-bin . jar,MSI安装后会有一个文件夹。里面会有文件MySQL-connector-Java-5 . 1 . 34-bin . jar。这里我们只需要这个MySQL-connector-Java-5.1 . xx-bin . jar。

将MySQL-connector-Java-x . x . x-bin . jar复制到Tomcat的安装bin目录D:& # 92;Tomcat 6.0 & # 92Lib(如果你安装msi文件,那么它可能在MySQL的安装目录的Tools文件夹里。我们不建议这样做,直接下载jar文件复制即可),然后在类路径中添加D:& # 92;Tomcat 6.0 & # 92lib & # 92MySQL-connector-Java-x . x . x-bin . jar就可以。复制步骤是为JSP连接数据库配置驱动程序。如果您使用的是MyEclipse附带的tomcat,请将jar文件直接复制到“Project & # 92WebRoot & # 92we b-INF & # 92;就在lib”路径下。

这种配置的目的是让java应用程序找到连接到mysql的驱动程序。

第三,JSP连接MySQL

建立学生数据库和stu_info表。现在我在尝试用jsp连接mysql。

创建测试页test.jsp

[java]查看纯文本

& lt%@页内容类型= & quot文本/html;charset = gb2312 & quot% & gt

& lt% @ page language = & quotjava & quot% & gt

& lt%@个页面导入= & quotcom . MySQL . JDBC . driver & quot;% & gt

& lt%@个页面导入= & quotjava.sql. * & quot% & gt

& lt%

//加载驱动程序

String driverName = & quotcom . MySQL . JDBC . driver & quot;;

//数据库信息

字符串用户名= & quotroot & quot;

//密码

字符串userPasswd = & quot123 & quot;

//数据库名称

String dbName = & quot学生& quot;

//表名

String tableName = & quotstu _ info & quot;

//将数据库信息字符串连接成一个完整的url(也可以直接写成url,单独写清楚,便于维护)

字符串url = & quotJDBC:MySQL://localhost/& quot;

dbName

& quot;马鞭用户= & quot

用户名

& quot;& password = & quot

user passwd;

class . for name(& quot;com . MySQL . JDBC . driver & quot;).new instance();

connection conn = driver manager . get connection(URL);

statement stmt = conn . create statement();

字符串sql = & quotSELECT * FROM & quot

tableName;

ResultSet RS = stmt . execute query(SQL);

out . print(& quot;id & quot);

out . print(& quot;

& quot);

out . print(& quot;名称& quot);

out . print(& quot;

& quot);

out . print(& quot;电话& quot);

out . print(& quot;& ltbr & gt& quot);

while(rs.next()) {

out . print(RS . getstring(1)

& quot;& quot);

out . print(& quot;

& quot);

out . print(RS . getstring(2)

& quot;& quot);

out . print(& quot;

& quot);

out . print(RS . getstring(3));

out . print(& quot;& ltbr & gt& quot);

}

out . print(& quot;& ltbr & gt& quot);

out . print(& quot;好的,数据库查询成功!& quot);

RS . close();

stmt . close();

conn . close();

% & gt

jsp连接数据库一直404?

可能是以下的其中一种情况:

一:连接URL格式出现了问题(Connection conn=DriverManager. getConnection("jdbc:mysql://localhost:3306/XX","root","XXXX"

) 二:驱动字符串出错(com.mysql.jdbc.Driver) 三:Classpath中没有加入合适的mysql_jdbc…