JSP连接数库

本章节假设您已经对JDBC有一定的了解。在开始学习JSP数据库访问前,请确保JDBC环境已经正确配置。
开启tomcat服务器与mysql
首先,让我们按照下面的步骤来创建一个简单的表并插入几条简单的记录:

创建表
在数据库中创建一个Employees表,步骤如下:

步骤1:
打开CMD,然后进入数据库安装目录:

C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

步骤2:

C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>

步骤3:
用create database语句建立一个新的数据库TEST:

mysql> create database TEST

步骤4:
在TEST数据库中创建Employee表:

mysql> use TEST;
mysql> create table Employees
    (
     id int not null,
     age int not null,
     first varchar (255),
     last varchar (255)
    );
Query OK, 0 rows affected (0.08 sec)
mysql>

插入数据记录
创建好Employee表后,往表中插入几条记录:

mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)
mysql>

SELECT操作
接下来的这个例子告诉我们如何使用JSTL SQL标签来运行SQL SELECT语句:

<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%
Connection con;
Statement sql;
ResultSet rs;
try{Class.forName("com.mysql.cj.jdbc.Driver");}
catch(Exception e){out.print(e);}
try{
    String uri="jdbc:mysql://localhost:3306/TEST";
    con=DriverManager.getConnection(uri,"root","");
    sql=con.createStatement();
    rs=sql.executeQuery("SELECT * FROM Employees");
    out.print("");
    out.print("");
    out.print("");while(rs.next()){
        out.print("");
        out.print("");
        out.print("");
        out.print("");
        out.print("");
        out.print("");}
    out.print("
"+"user_id"); out.print(""+"username"); out.print(""+"userpass"); out.print(""+"email"); out.print("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getString(3)+""+rs.getString(4)+"
"
); con.close(); } catch(SQLException e1){out.print(e1);} %> </body> </html>

你可能感兴趣的:(mysql,数据库,服务器)