jsp连接mysql数据库

时间:2021-06-18 06:33:35

1.新建一个Java web项目。

2.导入mysql驱动包。(这个跟上一篇写的Java连接mysql类似)

3.编写测试代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ page language="java" %>

<%@ page import="com.mysql.jdbc.Driver" %>

<%@ page import="java.sql.*" %>

<%
String driverName="com.mysql.jdbc.Driver";
String userName="root";
String userPasswd="root";
String dbName="goods";
String tableName="t_admin";
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql="SELECT * FROM "+tableName;
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData rmeta = rs.getMetaData();
int numColumns=rmeta.getColumnCount();
out.print("id"); out.print("|"); out.print("num"); out.print("<br>"); while(rs.next()) { out.print(rs.getString(1)+" "); out.print("|"); out.print(rs.getString(2)); out.print("<br>"); } out.print("<br>"); out.print("数据库操作成功,恭喜你"); rs.close(); statement.close(); connection.close(); %>

4.把mysql的驱动包拷贝到tomcat的lib目录一份。

5.打开浏览器,运行测试文件。

jsp连接mysql数据库