通过web服务器访问MYSQL数据库有以下几个过程:
1、在MySql下创建自己的数据库和自己的表单
2、连接数据库。
3、访问数据库
1、创建web工程 (服务器端)
在Myeclipse下新建一个web项目,为了好统一管理在WEB-INF下建一个web.xml用来加载服务器启动时的配置信息。这个文件是由大量的
web.xml实例如下:
1
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
5 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
6
7
8
9
10
11
12
13
14
15
2、为了方便对数据库验证信息的统一管理,在src目录下建一个DBConfig.properties文件。包含内容有:连接mysql数据库的驱动、url、用户名和密码。
1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/wirelessorder_db?useUnicode=true&characterEncoding=utf-8
3 username=rootpassword=123
3、连接数据库
a、可以先在src目录下建一个工具类DBUtil.java用于连接和关闭数据库。具体代码如下。
1 package com.amaker.util;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6 import java.util.Properties;
7
8
12 public class DBUtil {
13
14
17 public void closeConn(Connection conn){
18 try {
19 conn.close();
20 } catch (SQLException e) {
21 e.printStackTrace();
22 }
23 }
24
25
28 public Connection openConnection() {
29 Properties prop=new Properties();
30 String driver=null;
31 String url=null;
32 String username=null;
33 String password=null;
34
35 try {
36 prop.load(this.getClass().getClassLoader().getResourceAsStream(
37 "DBConfig.properties"));
38
39 driver=prop.getProperty("driver");
40 url=prop.getProperty("url");
41 username=prop.getProperty("username");
42 password=prop.getProperty("password");
43
44 Class.forName(driver);
45 return DriverManager.getConnection(url, username, password);
46 } catch (Exception e) {
47 e.printStackTrace();
48 }
49
50 return null;
51 }
52
53 }
b、再在src目录下新建一个Menu.java,用于设置获取其属性。
1 package com.amaker.entity;
2
3 public class Menu {
4 private int id;
5 private int price;
6 private int typeId;
7 private String name;
8 private String pic;
9 private String remark;
10
11 public int getId() {
12 return id;
13 }
14 public void setId(int id) {
15 this.id= id;
16 }
17 public String getName() {
18 return name;
19 }
20 public void setName(String name) {
21 this.name= name;
22 }
23 public String getPic() {
24 return pic;
25 }
26 public void setPic(String pic) {
27 this.pic= pic;
28 }
29 public int getPrice() {
30 return price;
31 }
32 public void setPrice(int price) {
33 this.price= price;
34 }
35 public String getRemark() {
36 return remark;
37 }
38 public void setRemark(String remark) {
39 this.remark= remark;
40 }
41 public int getTypeId() {
42 return typeId;
43 }
44 public void setTypeId(int typeId) {
45 this.typeId= typeId;
46 }
47
48 }
1
5 public class Update {
6 // 获得菜单列表
7 public List