本文章介绍JavaEE数据库链接需要注意的问题
本文章属于原创文章,转载时请注明出处
1、数据库脚本建立
这就需要你有mysql功底,在此介绍一种简单的工具,Navte for mysql
单击连接,选择MySQL,输入自己的用户名和密码,默认用户名为root,密码为自己的数据库密码一般为123456或者其他
建立之后双击连接名,输入密码,双击数据库名即可查看数据库的内容:右键即可建立新表
这里直接建立一个数据库,界面操作过于简单则不介绍
2、新建工程JavaMySQLTest,然后导入jar包,jar包位置不多说,见图
配置依赖 点击工程->右键->Properties->Java Build Path,然后选择相应的jar包
然后即可编码
下面直接贴代码:
首先看一下文件位置:
贴代码(实现简单的查询,应该够大家用的了吧 ‘邪恶脸’):
Student.java
package vo;
public class Student {
private String sno;
private String sex;
private int sage;
private String clno;
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public String getClno() {
return clno;
}
public void setClno(String clno) {
this.clno = clno;
}
}
Factory.java
package demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import vo.Student;
public class Factory {
private Connection conn;
private PreparedStatement pstm;
public Factory() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
}
public List<Student> findAll() throws Exception {
List<Student> all = new ArrayList<>();
try {
String url = "jdbc:mysql://127.0.0.1:3306/test"; //你的表名
String user = "root"; //你的用户名
String pass = "123456"; //你的密码
conn = DriverManager.getConnection(url ,user ,pass);
pstm = conn.prepareStatement("select * from student ; "); //你的查询语句
ResultSet rs = pstm.executeQuery();
Student student = null;
while(rs.next()) {
student = new Student();
student.setSno(rs.getString(1)); //按顺序获取表中资源
student.setSex(rs.getString(2));
student.setSage(rs.getInt(3));
student.setClno(rs.getString(4));
all.add(student);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return all;
}
}
index.jsp
<%@page import="java.util.Iterator"%>
<%@page import="vo.Student"%>
<%@page import="java.util.List"%>
<%@page import="demo.Factory"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<% request.setCharacterEncoding("UTF-8"); %>
<%
Factory factory = new Factory();
List<Student> all = factory.findAll();
Iterator<Student> iterator = all.iterator();
while(iterator.hasNext()) {
Student student = (Student) iterator.next();
%>
<%=student.getSno() %>
<%=student.getSex() %>
<%=student.getSage() %>
<%=student.getClno() %>
<%="\n" %>
<% } %>
</body>
</html>
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
重点来了:
编译工程的时候请将工程clean一下,如果不会,自己想办法吧,只能帮你到这了。。。。令注:基本的jsp技术就不用讲了吧,再讲也太没意思了吧
另附工程源码,打赏无价
工程源码