java连接mysql数据库(jsp显示和控制台显示)

news/2024/7/7 19:06:09

       很多事情,在我们没有做之前我们觉得好难,但是只要你静下心来,毕竟这些都是人搞出来的,只要你是人,那就一定可以明白。

配置:JDK1.8,MySQL5.7,eclipse:Neon Release (4.6.0),connector:mysql-connector-java-3.1.6-bin.jar

1、java连接数据库,并将结果显示在jsp页面中

这里需要用到tomcat服务器,怎么配置可以百度,下面会给出项目的工程配置和源代码以及实际运行效果。

这里,需要注意的一点是关于mysql-connector-java-3.1.6-bin.jar(版本随意,不要太旧就行)的配置,由于我新建的是“WEB->Dynamic Web project”,所以我们需要把mysql-connector-java-3.1.6-bin.jar放在WebContent->WEB-INF->lib文件夹下。不然会出现下图所示的错误。

image

由于是Dynamic Web project,所以不能采用Build Path->Configure Build Path->Add External JARs的形式添加mysql-connector-java-3.1.6-bin.jar,如果你执意要如此,还是会出现上图所示的找不到合适驱动的错误。

下面给出正确的工程拓扑结构及源码:

image

web.xml源码:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JDBCTest1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> 
</web-app>

index.jsp源码:

<%@ page language="java" import="java.sql.*" pageEncoding="UTF-8"%> 
<% try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("加载数据库驱动时抛出异常,内容如下:"); e.printStackTrace(); } Connection conn = DriverManager .getConnection( "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8","root", "w513723"); Statement stmt = conn.createStatement(); ResultSet rs = stmt .executeQuery("select * from user"); while (rs.next()) { out.println("ID:"+rs.getString(1)+"      "+"用户名:" + rs.getString(2)+"       " + "    密码:" + rs.getString(3)+".mdb<br/>"); } rs.close(); stmt.close(); conn.close(); 
%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> </body> 
</html>

user表结构:

image

实际运行效果:

image

 

2、java连接数据库,封装创建、插入、查找接口

这个没有太多讲的,这里与上面的区别在于这是普通的java工程,不是动态web项目,所以mysql-connector-java-3.1.6-bin.jar使用Build Path->Configure Build Path->Add External JARs添加即可。

(代码源于《JAVA web程序设计 慕课版》明日科技)有时间我会增减删除和更新表的操作。

工程拓扑结构:

image

源代码:

JDBCUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;public class JDBCUtil {/*使用静态代码块完成驱动的加载*/static {try {String driverName = "com.mysql.jdbc.Driver";Class.forName(driverName);} catch (Exception e) {e.printStackTrace();}}/*提供连接的方法*/public static Connection getConnection() {Connection con = null;try {//连接指定的MMySQL数据库,三个参数分别是:数据库地址、账号、密码con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf8", "root", "w513723");} catch (Exception e) {e.printStackTrace();}return con;}/*关闭连接的方法*/public static void close(ResultSet rs, Statement stmt, Connection con) {try {if (rs != null)rs.close();} catch (Exception ex) {ex.printStackTrace();}try {if (stmt != null)stmt.close();} catch (Exception ex) {ex.printStackTrace();}try {if (con != null)con.close();} catch (Exception ex) {ex.printStackTrace();}}
}

DaoTest.java

 

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class DaoTest {Connection con;Statement stmt;ResultSet rs;public Connection getCon() {return con;}public Statement getStmt() {return stmt;}public ResultSet getRs() {return rs;}public DaoTest(Connection con) {this.con = con;try {stmt = con.createStatement();} catch (SQLException e) {e.printStackTrace();}}public void createTable() throws SQLException {stmt.executeUpdate("DROP TABLE IF EXISTS `jdbc_test` ");//删除相同名称的表String sql = "create table jdbc_test(id int,name varchar(100)) ";stmt.executeUpdate(sql);//执行SQLSystem.out.println("jdbc_test表创建完毕");}public void insert() throws SQLException {String sql1 = "insert into jdbc_test values(1,'tom') ";String sql2 = "insert into jdbc_test values(2,'张三') ";String sql3 = "insert into jdbc_test values(3,'999') ";stmt.addBatch(sql1);stmt.addBatch(sql2);stmt.addBatch(sql3);int[] results = stmt.executeBatch();//批量运行sqlfor (int i = 0; i < results.length; i++) {System.out.println("第" + (i + 1) + "次插入返回" + results[0] + "条结果");}}public void select() throws SQLException {String sql = "select id,name from jdbc_test ";rs = stmt.executeQuery(sql);System.out.println("---数据库查询的结果----");System.out.println("id\tname");System.out.println("---------------------");while (rs.next()) {String id = rs.getString("id");String name = rs.getString("name");System.out.print(id + "\t" + name+"\n");}}public static void main(String[] args) {Connection con = JDBCUtil.getConnection();DaoTest dao = new DaoTest(con);try {dao.createTable();dao.insert();dao.select();} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtil.close(dao.getRs(), dao.getStmt(), dao.getCon());}}}

程序运行控制台输出:

image

数据库查询结构:

image

增加删除和更新操作(其实很简单的,当初为什么没有写呢?被吓到了???)

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class DaoTest {Connection con;Statement stmt;ResultSet rs;public Connection getCon() {return con;}public Statement getStmt() {return stmt;}public ResultSet getRs() {return rs;}public DaoTest(Connection con) {this.con = con;try {stmt = con.createStatement();} catch (SQLException e) {e.printStackTrace();}}public void createTable() throws SQLException {stmt.executeUpdate("DROP TABLE IF EXISTS `jdbc_test` ");//删除相同名称的表String sql = "create table jdbc_test(id int,name varchar(100)) ";stmt.executeUpdate(sql);//执行SQLSystem.out.println("jdbc_test表创建完毕");}public void insert() throws SQLException {String sql1 = "insert into jdbc_test values(1,'tom') ";String sql2 = "insert into jdbc_test values(2,'张三') ";String sql3 = "insert into jdbc_test values(3,'999') ";stmt.addBatch(sql1);stmt.addBatch(sql2);stmt.addBatch(sql3);int[] results = stmt.executeBatch();//批量运行sqlfor (int i = 0; i < results.length; i++) {System.out.println("第" + (i + 1) + "次插入返回" + results[0] + "条结果");}}public void select() throws SQLException {String sql = "select id,name from jdbc_test ";rs = stmt.executeQuery(sql);System.out.println("---数据库查询的结果----");System.out.println("id\tname");System.out.println("---------------------");while (rs.next()) {String id = rs.getString("id");String name = rs.getString("name");System.out.print(id + "\t" + name+"\n");}}public void delete() throws SQLException{String sql="delete from jdbc_test where id in (1,2)";int tmp=stmt.executeUpdate(sql);   //这里函数的返回值表示成功删除了多少条数据if (tmp<1){System.out.println("要删除的数据不存在或删除错误!");}else{System.out.println("成功删除"+tmp+"条数据");  }}public void update() throws SQLException{String sql="update jdbc_test set name='shuai' where id=3";int tmp=stmt.executeUpdate(sql);   //这里函数的返回值表示成功更新了多少条数据if (tmp<1){System.out.println("需要更新的数据不存在或更新错误!");}else{System.out.println("成功更新"+tmp+"条数据"); }}public static void main(String[] args) {Connection con = JDBCUtil.getConnection();DaoTest dao = new DaoTest(con);try {dao.createTable();dao.insert();dao.select();dao.delete();dao.select();dao.update();dao.select();} catch (SQLException e) {e.printStackTrace();} finally {JDBCUtil.close(dao.getRs(), dao.getStmt(), dao.getCon());}}}

运行截图:

image

转载于:https://www.cnblogs.com/audi-car/p/5785217.html


http://lihuaxi.xjx100.cn/news/243927.html

相关文章

汇编与反汇编

本来是打算学习linux的&#xff0c;然后做运维。可是在学习的过程中总是感觉不痛快&#xff0c;抓不住重点&#xff0c;就向下学c语言&#xff1b;学习c语言又发现有许多知识点抓不住重点&#xff0c;就向下学习汇编、学习微机原理&#xff0c;发现汇编与反汇编才是学习计算机科…

Tslib移植与分析【转】

转自&#xff1a;http://blog.csdn.net/water_cow/article/details/7215308 目标平台&#xff1a;LOONGSON-1B开发板&#xff08;mips32指令集&#xff09;编译平台&#xff1a;x86PC--VMware6.5--Ubuntu10.04&#xff08;下面简称“ubuntu系统”&#xff09; 或&am…

总结:如何使用redis缓存加索引处理数据库百万级并发

前言&#xff1a;事先说明&#xff1a;在实际应用中这种做法设计需要各位读者自己设计&#xff0c;本文只提供一种思想。准备工作&#xff1a;安装后本地数redis服务器&#xff0c;使用mysql数据库&#xff0c;事先插入1000万条数据&#xff0c;可以参考我之前的文章插入数据&a…

Linux----进程概念

程序 : 程序指的是一系列有逻辑, 有顺序结构的指令.进程 : 进程从两个角度来说:1 用户角度: 进程从用户角度来说就是运行中的程序2 操作系统的角度: 进程是操作系统对运行中程序的描述信息, 叫做进程描述符(程序控制块)简称PCBPCB : 在Linux下PCB指的是在内核中的task_struct 结…

DOMContentLoaded 与onload区别以及使用

一、何时触发这两个事件&#xff1f; 1、当 onload 事件触发时&#xff0c;页面上所有的DOM&#xff0c;样式表&#xff0c;脚本&#xff0c;图片&#xff0c;flash都已经加载完成了。 2、当 DOMContentLoaded 事件触发时&#xff0c;仅当DOM加载完成&#xff0c;不包括样式表&…

移动端开发者眼中的前端开发流程变迁与前后端分离

写在最开始 这是一篇面向移动端开发者的科普性文章&#xff0c;从前端开发的最初流程开始&#xff0c;结合示范代码&#xff0c;讨论开发流程的演变过程&#xff0c;希望能覆盖一部分前端开发技术栈&#xff0c;从而对前端开发的相关概念形成初步的认识。 本文会提供一些示范代…

最多显示6行并且最多显示三条文本

为什么80%的码农都做不了架构师&#xff1f;>>> private void setCommentContent(ViewHolder vh, String feedId, int commentNum, ArrayList<CommentItem> comment_lists){if(commentNum < 0 || comment_lists null || comment_lists.isEmpty()){for(in…

python--安装PIL

PIL&#xff1a;Python Imaging Library&#xff0c;已经是Python平台事实上的图像处理标准库了。PIL功能非常强大&#xff0c;但API却非常简单易用。 安装PIL 在Debian/Ubuntu Linux下直接通过apt安装&#xff1a; $ sudo apt-get install python-imaging在windows平台要到PIL…