<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">首先下载并正确安装mysql,配置环境变量,为的是方便导入数据。</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">mysql - t < employees.sql -u root -p test,test为mysql内置的一个数据库名,你也可以自己建一个数据库。这样就将sql文件导入了。</span>
create table a(
id int,
val int
);
insert into a values(1,11),(2.12),(3,13);
我们在test下建一个表,里面放三行数据测试jdbc程序用。
在myeclipse下建一个test.java文件,这就是我们的测试程序啦。完整的jdbc步骤是这样的,了解了会写了我们以后就不用去写了,并且有很多封装好的程序可供我们直接调用。
第一步:注册驱动程序class.forname("com.mysql.jdbc.Driver"),你也可以使用这个包下的驱动org.gjt.mm.mysql
第二步:创建连接Connection con = DriverManager.getConnection(url,user,password),url切记不能写错,格式为“jdbc:mysql://host:port/database”,user,password为你的用户名和密码
第三步: 创建执行SQL语句的对象
你也可以用这种创建:Statement stmt = con.createStatement(),缺点是不灵活,不能独立设置参数,因此一般不用。
一般我们会把第二种创建方法封装在一个函数中,PreparedStatement stmt = con.prepareStatement(String sql)
封装如下:
private void setPrepareStatementParams(String sql, Object[] params)
throws SQLException
{
pstm = conn.prepareStatement(sql); // 获取对象
if (params != null)
{
for (int i = 0; i < params.length; i++) // 遍历参数列表填充参数
{
pstm.setObject(i + 1, params[i]);
}
}
}
再封装一下excute方法
public ResultSet executeQuery(String sql, Object[] params)
throws SQLException
{ // 执行查询数据库接口
ResultSet rs = null;
manager.setPrepareStatementParams(sql, params); // 填充参数
rs = pstm.executeQuery(); // 执行查询操作
return rs;
}
这样我们就直接调用executeQuery方法,通过传递查询的sql语句和参数就可以达到查询的目的。同理,增删改查都封装成对应的函数,其实只有两个,一个是executeQuery,一个是executeUpdate。这样用起来会方便很多,整个作为一个工具类放在那边。用到对应的增删改查操作就new一个对象调用对应的方法。
第四步:执行操作
stmt.executeQuery(query) 另一组stmt..execute(),因为第二组的sql语句已经在前面传入了,这边直接调用一下执行操作即可。
第五步:执行结果的处理
增删改查中涉及执行的结果只有查,其他都不返回结果集的。结果集ResultSet在executeQurey方法中有返回,通过next方法去遍历字段名得到对应的值,相关的知识会有集合操作和迭代器。
第六步: 释放资源
关闭结果集,关闭statement对象,关闭连接。这里我们也可以将这些固定操作封装在我们的工具类中。
在写代码之前,我们在eclipse 中先添加Mysql的jar包。这里我用的是mysql-connector-java-5.1.6-bin.jar,根据自己的mysql版本来把。
据此我们就可以写出我们的第一段jdbc代码了
package com.Action;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
/**
* JDBC
*
*/
public class test {
public static void main(String[] args) throws Exception {
Class.forName("org.gjt.mm.mysql.Driver");//注册驱动程序
//mysql数据库
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="1900";
//创建连接
Connection con = (Connection) DriverManager.getConnection(url, user, password);
//创建执行SQL语句的对象
Statement stmt = (Statement) con.createStatement();
String sql="select * from a";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("id")+"|"+(rs.getInt("val")));
}
}
}
运行结果可以去和数据库中的做个比较,其他增删改的操作同理都可以做到。
我们的数据库在本地测试成功的情况下,我就拿到web项目上了,一开始总是会出现驱动找不到的情况,后来才发现是没有在tomcat的webapps目录下对应的项目下有个lib文件,我们应该将mysql的jar包也拷一份过去,这样就不会出问题了。
以简单的注册登陆页面为例,我们先建一个web项目Ali,下属页面有register.jsp和login.jsp
在表单中我们传入的值就是数据库中建立的表的字段的值。这一步通过struts2去传递的。我们有对应的LoginAction和RegisterAction.
我在这两个Action 中负责数据库的插入和查询工作。RegisterAction中一定是要把表单传过来的值insert到数据库中的表下的。(前提现在数据库下建好表)
具体执行过程见代码。然后在LoginAciton中负责验证用户名密码是否正确,说白了就是在我们的工具类中添加一个函数,用来验证我们的用户名密码是否存在于数据库中,怎么验证呢,很简单,执行查询操作select * from customer where username=? && password=?这样就可以找到是否有记录了,返回true or false供外部调用。
这样我们就写成了一个简单的表单提交和数据库连接程序。连接了前台网页输入和后台数据库数据存储。
以下是我web项目中的部分类
customer类
package com.bean;
import java.util.Date;
public class Customer {
private Integer id;
private String name;
private String password;
private String sex;
private Integer age;
private Date birthday;
private String email;
private String mobile;
private Date create_date;
private Date update_date;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public Date getUpdate_date() {
return update_date;
}
public void setUpdate_date(Date update_date) {
this.update_date = update_date;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", password="
+ password + ", sex=" + sex + ", age=" + age + ", birthday="
+ birthday + ", email=" + email + ", mobile=" + mobile
+ ", create_date=" + create_date + ", update_date="
+ update_date + "]";
}
}
customerDao类,即我们前面说的工具类,提供增删改查的功能和校验功能
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import com.bean.Customer;
public class CustomerDao {
SqlManager manager;
String sql = "";
ResultSet resultSet;
public CustomerDao() throws Exception {
manager = SqlManager.createInstance();
}
public void addCustomer(Customer c) throws Exception {
int id = countCustomer()+1;
sql = "insert into customer "
+ "(id,username,password,sex,age,birthday,email,mobile,create_date,update_date)"
+ " values(?,?,?,?,?,?,?,?,?,?)";
Object[] params = new Object[] {
id,
c.getName(),
c.getPassword(),
c.getSex(),
c.getAge(),
c.getBirthday(),
c.getEmail(),
c.getMobile(),
new Date(),
new Date()
};
manager.connectDB();
manager.executeUpdate(sql, params);
manager.closeDB();
}
/**
* 获取id
*
* @return
* @throws Exception
*/
private int countCustomer() throws Exception {
manager.connectDB();
sql = "select * from customer";
resultSet = manager.executeQuery(sql, null);
if (resultSet.last()) {
return resultSet.getRow();
} else {
return 0;
}
}
/*
* 更新
*/
public void updateCustomer(Customer g) throws Exception {
sql = "";
Object[] params = new Object[] { };
manager.connectDB();
manager.executeUpdate(sql, params);
manager.closeDB();
}
/*
* 删除
*/
public void delCustomer(Integer id) throws SQLException {
sql = "delete from customer " + "where id=?";
manager.connectDB();
manager.executeUpdate(sql, new Object[] { id });
manager.closeDB();
}
/*
* 查询
*/
public Customer get(Integer id) throws SQLException {
sql = "select * from customer where id=?";
Customer c = new Customer();
manager.connectDB();
resultSet = manager.executeQuery(sql, new Object[] { id });
while (resultSet.next()) {
}
manager.closeDB();
return c;
}
public boolean cusExisit(String username,String password) throws SQLException{
sql = "select * from customer where username=?&&password=?";
manager.connectDB();
resultSet = manager.executeQuery(sql, new Object[]{username,password});
System.out.println("验证开始");
if(resultSet.next()){
return true;
}
return false;
}
}
对应的register.jsp页面
<div class="regpage">
<form action="/Ali/registerAction.action" method="post">
<table>
<tr>
<td colspan="2">填写注册信息</td>
</tr>
<tr>
<td>用户名</td>
<td><input type="text" name="name" size="10"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password" size="10"></td>
</tr>
<tr>
<td>性别</td>
<td><input type="radio" name="sex" value="男">男<input type="radio" name="sex" value="女">女</td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age" size="10"></td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birthday" size="10"></td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email" size="10"></td>
</tr>
<tr>
<td>手机</td>
<td><input type="text" name="mobile" size="10"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="注册"></td>
</tr>
</table>
</form>
</div>
对应的Action-RegisterAction
package com.action;
import java.util.Date;
import com.bean.Customer;
import com.dao.CustomerDao;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String name;
private String password;
private String sex;
private Integer age;
private Date birthday;
private String email;
private String mobile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Override
public String execute(){
CustomerDao dao;
Customer customer = new Customer();
try {
dao = new CustomerDao();
if(null!=name){
customer.setName(name);
System.out.println("name:"+name);
}
if(null!=password){
customer.setPassword(password);
System.out.println("password:"+password);
}
if(null!=sex){
customer.setSex(sex);
System.out.println(sex);
}
if(null!=age){
customer.setAge(age);
System.out.println(age);
}
if(null!=birthday){
customer.setBirthday(birthday);
System.out.println(birthday);
}
if(null!=email){
customer.setEmail(email);
System.out.println(email);
}
if(null!=mobile){
customer.setMobile(mobile);
System.out.println(mobile);
}
dao.addCustomer(customer);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "input";
}
}
}
在执行完页面上的注册过程后,数据库对应就会出现一行记录。
注册完成跳转到的是login.jsp页面,我们只有输入正确的用户名密码才能登陆成功进入到welcom.jsp页面。对应的配置在struts.xml下完成
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="Ali" namespace="/" extends="struts-default">
<action name="loginAction" class="com.action.LoginAction">
<result name="success">
/page/welcome.jsp
</result>
<result name="input">
/page/login.jsp
</result>
</action>
<action name="registerAction" class="com.action.RegisterAction">
<result name="success">
/page/login.jsp
</result>
<result name="input">
/page/register.jsp
</result>
</action>
</package>
</struts>
完成对应的页面映射后,我们建立了Login页面和LoginAction
login页面比较庞大,只截取部分
<div class="login">
<form action="/Ali/loginAction.action" method="post">
<table>
<tr>
<td>用户名:<input type="text" name="username" /><br>
</td>
<td>密码: <input type="password" name="password">
</td>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
</div>
执行完成后,我们在LoginAction中写如下验证,调用的是工具类下的验证函数。
public String execute() throws Exception {
CustomerDao dao =new CustomerDao();
if(dao.cusExisit(username, password))
return "success";
return "input";
}
整个页面的流程就是这样了。由于没有用到jstl标签,后期会做改进。