常见的B/S的程序结构都有和数据库的交互,本示例中通过一个简单的增删改查的列子,介绍LAJP的通常使用方式。


一、创建库表结构,使用Mysql

1. 先创建用户:

下面两条语句创建用户’ali’,其登录密码’ali’,可以从本地和网络登录,拥有数据库所有权限:

1. mysql> GRANT ALL PRIVILEGES ON *.* TO ‘ali’@‘localhost’ IDENTIFIED BY ‘ali’ WITH GRANTOPTION;

2. mysql> GRANT ALL PRIVILEGES ON *.* TO ‘ali’@‘%’ IDENTIFIED BY ‘ali’ WITH GRANT OPTION;

2. 使用用户ali登录Mysql:

1. $ mysql -u ali -pali

3. 创建数据库demo_users, 使用utf8字符集

1. mysql> CREATE DATABASE demo_users CHARACTER SET utf8;

4. 创建表

1. mysql> CREATE TABLE demo(

2.     id MEDIUMINT NOT NULL AUTO_INCREMENT,

3.     login varchar(20) NOT NULL,

4.     passwd varchar(20) NOT NULL,

5.     userName varchar(10) NOT NULL,

6.     age SMALLINT NOT NULL,

7.     sex TINYINT NOT NULL,

8. PRIMARY KEY(id));

demo中字段含义如下:

id: 主键,自增序列
login: 用户帐号
passwd: 用户密码
userName: 用户名称
age: 用户年龄
sex: 用户性别,0女性 1男性

二、Java

在LAJP架构中,Java负责和数据库交互,这里使用开源的组件搭建Java和数据库的连接:

* 数据库JDBC驱动:Mysql官方提供的mysql-connector-java
* 数据库连接池:使用开源的c3p0
* 日志组件:最常用的log4j

1. 首先,编写获得数据库交互的工具类

1.

2. package com.googlecode.lajp.mysqldemo;

3. import java.beans.PropertyVetoException;

4. import java.sql.Connection;

5. import java.sql.SQLException;

6. import org.apache.log4j.Logger;

7. import com.mchange.v2.c3p0.ComboPooledDataSource;

8.

9. public class DBUtil

10. {

11. static Logger log = Logger.getLogger(DBUtil.class);

12.

13. private static ComboPooledDataSource cpds;

14.

15. public static final void init()

16. {

17.             cpds = new ComboPooledDataSource();

18. try

19. {

20.                 cpds.setDriverClass("com.mysql.jdbc.Driver");

21. }

22. catch (PropertyVetoException e)

23. {

24.                 log.error("加载数据库驱动异常", e);

25. throw new RuntimeException("Can’t load Driver: om.mysql.jdbc.Driver" );

26. }

27.             cpds.setJdbcUrl("jdbc:mysql://127.0.0.1/demo_users?characterEncoding=utf-8");

28.             cpds.setUser("ali");

29.             cpds.setPassword("ali");

30. }

31.

32. public static Connection getConn() throws SQLException

33. {

34. return cpds.getConnection();

35. }

36. }

在类DBUtil中,编写了两个方法,init()用来初始化c3p0数据库连接池,20行加载JDBC驱动,027~029行声明连接参数,”jdbc:mysql://127.0.0.1/demo_users?characterEncoding=utf-8″表示连接到本机的 demo_users库,字符集为utf-8。getConn()方法是公用的获取数据库连接的方法。

2. JavaBean对象

对于Java面向对象语言,习惯以对象方式映射数据库表,这里编写一个和表demo映射的JavaBean类:

1.

2. package com.googlecode.lajp.mysqldemo;

3.

4. public class User

5. {

6. /** ID */

7. private int id;

8. /** 帐号 */

9. private String login;

10. /** 密码 */

11. private String passwd;

12. /** 用户名 */

13. private String userName;

14. /** 年龄 */

15. private int age;

16. /** 性别(true:女) */

17. private boolean girl;

18.

19.         ……getter 和 setter 方法

20. }

User中的每个属性和demo表的字段对应,并具有同业务含义相符合的数据类型。

3. 服务方法

最后编写PHP调用的服务方法,代码比较长,这里只将第一个方法(增加方法)显示完整,其他方法只显示主要逻辑代码:

1.

2. package com.googlecode.lajp.mysqldemo;

3.

4. import java.sql.Connection;

5. import java.sql.PreparedStatement;

6. import java.sql.ResultSet;

7. import java.sql.SQLException;

8. import java.util.ArrayList;

9.

10. import org.apache.log4j.Logger;

11.

12. /**

13.  * Java服务

14.  * @author diaoyf

15.  *

16.  */

17. public class JavaService

18. {

19. static Logger log = Logger.getLogger(JavaService.class);

20.

21. /**

22.      * 增加用户服务

23.      * @param newUser 用户对象

24.      * @throws Exception

25.      */

26. public static final void addUser(User newUser) throws Exception

27. {

28. Connection conn = null;

29. PreparedStatement stmt = null;

30. try

31. {

32.             conn = DBUtil.getConn();

33.

34. StringBuffer sql = new StringBuffer();

35.             sql.append("insert into demo");

36.             sql.append("(");

37.             sql.append("  login,");

38.             sql.append("  passwd,");

39.             sql.append("  userName,");

40.             sql.append("  age,");

41.             sql.append("  sex ");

42.             sql.append(")values(");

43.             sql.append("  ?,");

44.             sql.append("  ?,");

45.             sql.append("  ?,");

46.             sql.append("  ?,");

47.             sql.append("  ? ");

48.             sql.append(")");

49.

50.             stmt = conn.prepareStatement(sql.toString());

51.             stmt.setString(1, newUser.getLogin());

52.             stmt.setString(2, newUser.getPasswd());

53.             stmt.setString(3, newUser.getUserName());

54.             stmt.setShort(4, (short)newUser.getAge());

55.             stmt.setShort(5, (short)(newUser.isGirl() ? 0 : 1));   

56.

57.             stmt.execute();

58. }

59. catch (Exception e)

60. {

61.             log.error("增加新用户异常", e);

62.

63. throw e;

64. }

65. finally

66. {

67. try

68. {

69. if (conn != null)

70. {

71.                     conn.close();

72. }

73. }

74. catch (SQLException e)

75. {

76. }

77. }

78. }

79.

80. /**

81.      * 删除用户服务

82.      * @param id 用户ID

83.      * @throws Exception

84.      */

85. public static final void delUser(int id)throws Exception

86. {

87. //….

88.

89. StringBuffer sql = new StringBuffer();

90.             sql.append("delete from demo where id = ?");

91.

92.             stmt = conn.prepareStatement(sql.toString());

93.             stmt.setInt(1, id);

94.

95.             stmt.execute();

96.

97. //….

98. }

99.

100. /**

101.      * 修改用户属*********

102.      * @param user

103.      * @throws Exception

104.      */

105. public static final void modifyUser(User user)throws Exception

106. {

107. //….

108.

109. StringBuffer sql = new StringBuffer();

110.             sql.append("update demo set ");

111.             sql.append("  login = ?,");

112.             sql.append("  passwd = ?,");

113.             sql.append("  userName = ?,");

114.             sql.append("  age = ?,");

115.             sql.append("  sex = ? ");

116.             sql.append("  where id = ?");

117.

118.             stmt = conn.prepareStatement(sql.toString());

119.             stmt.setString(1, user.getLogin());

120.             stmt.setString(2, user.getPasswd());

121.             stmt.setString(3, user.getUserName());

122.             stmt.setShort(4, (short)user.getAge());

123.             stmt.setShort(5, (short)(user.isGirl() ? 0 : 1));

124.             stmt.setInt(6, user.getId());

125.

126.             stmt.executeUpdate();

127.

128. //….

129. }

130.

131. /**

132.      * 根据ID查询用户服务

133.      * @param id

134.      * @return 用户对象

135.      * @throws Exception

136.      */

137. public static final User getUser(int id)throws Exception

138. {

139. //….

140.

141. StringBuffer sql = new StringBuffer();

142.             sql.append("select * from demo where id = ?");

143.

144.             stmt = conn.prepareStatement(sql.toString());

145.             stmt.setInt(1, id);

146.

147.             rs = stmt.executeQuery();

148.

149. if (rs.next())

150. {

151.                 User user = new User();

152.                 user.setId(rs.getInt("id"));

153.                 user.setLogin(rs.getString("login"));

154.                 user.setPasswd(rs.getString("passwd"));

155.                 user.setUserName(rs.getString("userName"));

156.                 user.setAge(rs.getShort("age"));

157.                 user.setGirl((rs.getShort("sex") == 0) ? true : false);

158.

159. return user;

160. }

161. else

162. {

163. throw new Exception("查询不到用户, >12. ?>

相关文章:

  • 2021-11-28
  • 2021-11-10
  • 2021-09-21
  • 2021-09-30
  • 2021-11-05
  • 2019-12-15
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-21
  • 2021-09-28
  • 2021-10-20
相关资源
相似解决方案