flex与java实现增删改查
用的是MySQL数据库。
1,建一个userdb库,再建userinfo表,字 段:id(int),username(varchar),password(varchar)。
- create database userdb;
- use userdb;
- create table userinfo(
- id int(10) not null auto_increment,
- username varchar(20),
- password varchar(20),
- primary key(id));
2,DBConnection.java
- package com.datainfo;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- public class DBConnection {
- public static Connection getConnection() throws ClassNotFoundException,
- SQLException {
- Connection conn = null;
- String driver = "com.mysql.jdbc.Driver";
- String url = "jdbc:mysql://localhost:3306/userdb";
- String username = "root";
- String password = "mysql";
- Class.forName(driver);
- conn = DriverManager.getConnection(url, username, password);
- return conn;
- }
- }
3,User.java
- package com.datainfo;
- public class User {
- private int id;
- private String username;
- private String password;
- public User() {
- }
- /**
- * @return the id
- */
- public int getId() {
- return id;
- }
- /**
- * @param id
- * the id to set
- */
- public void setId(int id) {
- this.id = id;
- }
- /**
- * @return the username
- */
- public String getUsername() {
- return username;
- }
- /**
- * @param username
- * the username to set
- */
- public void setUsername(String username) {
- this.username = username;
- }
- /**
- * @return the password
- */
- public String getPassword() {
- return password;
- }
- /**
- * @param password
- * the password to set
- */
- public void setPassword(String password) {
- this.password = password;
- }
- }
4,UserDAO.java
- package com.datainfo;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import com.datainfo.DBConnection;
- public class UserDAO {
- public ArrayList getUserList() throws ClassNotFoundException, SQLException {
- Connection conn = DBConnection.getConnection();
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select * from userinfo");
- ArrayList userList = null;
- try {
- userList = new ArrayList();
- while (rs.next()) {
- User user = new User();
- user.setId(rs.getInt("id"));
- user.setUsername(rs.getString("username"));
- user.setPassword(rs.getString("password"));
- userList.add(user);
- }
- rs.close();
- stmt.close();
- conn.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return userList;
- }
- public void addUser(User user) throws ClassNotFoundException, SQLException {
- Connection conn = DBConnection.getConnection();
- String sql = "insert into userinfo (username,password) values (?,?)";
- try {
- PreparedStatement pstmt = conn.prepareStatement(sql);
- pstmt.setString(1, user.getUsername());
- pstmt.setString(2, user.getPassword());
- pstmt.executeUpdate();
- pstmt.close();
- conn.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void updataUser(User user) throws ClassNotFoundException,
- SQLException {
- Connection conn = DBConnection.getConnection();
- String sql = "update userinfo set username=?,password=? where id=?";
- try {
- PreparedStatement pstmt = conn.prepareStatement(sql);
- pstmt.setString(1, user.getUsername());
- pstmt.setString(2, user.getPassword());
- pstmt.setInt(3, user.getId());
- pstmt.executeUpdate();
- pstmt.close();
- conn.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void deleteUser(User user) throws ClassNotFoundException,
- SQLException {
- Connection conn = DBConnection.getConnection();
- String sql = "delete from userinfo where id =?";
- try {
- PreparedStatement pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, user.getId());
- pstmt.executeUpdate();
- pstmt.close();
- conn.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
5,配置文件remoting-config.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <service id="remoting-service" class="flex.messaging.services.RemotingService">
- <adapters>
- <adapter-definition id="java-object"
- class="flex.messaging.services.remoting.adapters.JavaAdapter"
- default="true" />
- </adapters>
- <default-channels>
- <channel ref="my-amf" />
- </default-channels>
- <destination id="userDao">
- <properties>
- <source>com.datainfo.UserDAO</source>
- </properties>
- </destination>
- </service>
6,以下是flex端,UserFlex.as
- package com.flex
- {
- [Bindable]
- [RemoteClass(alias="com.datainfo.User")]
- public class UserFlex
- {
- // public function UserFlex{
- //
- // }
- public var id:int;
- public var username:String;
- public var password:String;
- // 如果用private,就需要写上get/set
- //
- // public function get id():int{
- // return this.id;
- // }
- // public function set id():int{
- // this.id = id;
- // }
- //
- // public function get username():String{
- // return this.username;
- // }
- // public function set username():String{
- // this.username = username;
- // }
- //
- // public function get password():String{
- // return this.password;
- // }
- // public function set password():String{
- // this.password = password;
- // }
- }
- }
7,自定义的DataGrid组件,用以双击修改数据DoubleClickDataGrid.as
- package com.flex
- {
- import flash.events.MouseEvent;
- import mx.controls.DataGrid;
- import mx.controls.dataGridClasses.DataGridColumn;
- import mx.controls.listClasses.IDropInListItemRenderer;
- import mx.controls.listClasses.IListItemRenderer;
- import mx.core.EventPriority;
- import mx.events.DataGridEvent;
- public class DoubleClickDataGrid extends DataGrid
- {
- public function DoubleClickDataGrid()
- {
- //TODO: implement function
- super();
- doubleClickEnabled = true;
- }
- override protected function mouseDoubleClickHandler(event:MouseEvent):void
- {
- var dataGridEvent:DataGridEvent;
- var r:IListItemRenderer;
- var dgColumn:DataGridColumn;
- r = mouseEventToItemRenderer(event);
- if (r && r != itemEditorInstance)
- {
- var dilr:IDropInListItemRenderer = IDropInListItemRenderer(r);
- if (columns[dilr.listData.columnIndex].editable)
- {
- dgColumn = columns[dilr.listData.columnIndex];
- dataGridEvent = new DataGridEvent(DataGridEvent.ITEM_EDIT_BEGINNING, false, true);
- // ITEM_EDIT events are cancelable
- dataGridEvent.columnIndex = dilr.listData.columnIndex;
- dataGridEvent.dataField = dgColumn.dataField;
- dataGridEvent.rowIndex = dilr.listData.rowIndex + verticalScrollPosition;
- dataGridEvent.itemRenderer = r;
- dispatchEvent(dataGridEvent);
- }
- }
- super.mouseDoubleClickHandler(event);
- }
- override protected function mouseUpHandler(event:MouseEvent):void
- {
- var r:IListItemRenderer;
- var dgColumn:DataGridColumn;
- r = mouseEventToItemRenderer(event);
- if (r)
- {
- var dilr:IDropInListItemRenderer = IDropInListItemRenderer(r);
- if (columns[dilr.listData.columnIndex].editable)
- {
- dgColumn = columns[dilr.listData.columnIndex];
- dgColumn.editable = false;
- }
- }
- super.mouseUpHandler(event);
- if (dgColumn)
- dgColumn.editable = true;
- }
- }
- }
8,页面显示,testflex.mxml
- <?xml version="1.0" encoding="utf-8"?>
- <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
- xmlns:s="library://ns.adobe.com/flex/spark"
- xmlns:mx="library://ns.adobe.com/flex/mx"
- xmlns:locdg="com.flex.*"
- creationComplete="initApp()"
- minWidth="955" minHeight="600">
- <fx:Declarations>
- <!-- 将非可视元素(例如服务、值对象)放在此处 -->
- <s:RemoteObject id="userdata" destination="userDao" result="onResult(event)" fault="onFault(event)" />
- <!--<s:method name="getUserList" result="onResult(event)" fault="onFault(event)" />-->
- <s:RemoteObject id="adduserdata" destination="userDao" result="addResult(event)" fault="addFault(event)" />
- <s:RemoteObject id="updatauserdata" destination="userDao" result="updataResult(event)" fault="updataFault(event)" />
- <s:RemoteObject id="deleteuserdata" destination="userDao" result="deleteResult(event)" fault="deleteFault(event)" />
- </fx:Declarations>
- <fx:Script>
- <!--[CDATA[
- import com.flex.UserFlex;
- import mx.collections.ArrayCollection;
- import mx.controls.Alert;
- import mx.managers.CursorManager;
- import mx.rpc.events.FaultEvent;
- import mx.rpc.events.ResultEvent;
- public var userFlex:UserFlex = new UserFlex();
- public var result:Object = new Object();
- [Bindable]
- public var users:ArrayCollection = new ArrayCollection();
- public function initApp():void{
- // userdata.getUserList();
- }
- public function click_handler(event:Event):void{
- CursorManager.setBusyCursor();
- info.text = "正在查 询...";
- userdata.getUserList();
- }
- public function adduser_handler(event:Event):void{
- if(username.text != "" && password.text != ""){
- CursorManager.setBusyCursor();
- addinfo.text = "正在添加...";
- userFlex.username = username.text;
- userFlex.password = password.text;
- adduserdata.addUser(userFlex);
- }else{
- addinfo.text = " 用户名和密码不能为空";
- }
- }
- public function updataUser(event:Event):void{
- if(userlist.selectedItem.username != "" && userlist.selectedItem.password != ""){
- CursorManager.setBusyCursor();
- info.text = "正在 更新...";
- userFlex.id = userlist.selectedItem.id;
- userFlex.username = userlist.selectedItem.username;
- userFlex.password = userlist.selectedItem.password;
- updatauserdata.updataUser(userFlex);
- }
- // Alert.show("确认修改?");
- }
- public function deleteUser(event:Event):void{
- CursorManager.setBusyCursor();
- info.text = "正在正在删 除...";
- userFlex.id = userlist.selectedItem.id;
- deleteuserdata.deleteUser(userFlex);
- }
- public function onResult(event:ResultEvent):void{
- users = event.result as ArrayCollection;
- CursorManager.removeBusyCursor();
- if(users.length==0){
- info.text="取数据成功,为空";
- }else{
- info.text = " 取数据成功";
- }
- }
- public function onFault(event:FaultEvent):void{
- CursorManager.removeBusyCursor();
- info.text="取数据失败";
- }
- public function addResult(event:ResultEvent):void{
- CursorManager.removeBusyCursor();
- userdata.getUserList();
- username.text = "";
- password.text = "";
- addinfo.text = " 添加成功";
- // info.text = "取数据成功";
- }
- public function addFault(event:FaultEvent):void{
- CursorManager.removeBusyCursor();
- addinfo.text="添加失败";
- }
- public function updataResult(event:ResultEvent):void{
- CursorManager.removeBusyCursor();
- userdata.getUserList();
- info.text = "修改数 据成功";
- }
- public function updataFault(event:FaultEvent):void{
- CursorManager.removeBusyCursor();
- info.text="修改数据失 败";
- }
- public function deleteResult(event:ResultEvent):void{
- CursorManager.removeBusyCursor();
- userdata.getUserList();
- info.text = "刪除数据成 功";
- }
- public function deleteFault(event:FaultEvent):void{
- CursorManager.removeBusyCursor();
- info.text="刪除数据失败";
- }
- ]]-->
- </fx:Script>
- <locdg:DoubleClickDataGrid x="61" y="189" id="userlist" dataProvider="{users}" editable="true">
- <locdg:columns>
- <mx:DataGridColumn headerText="ID号" dataField="id" editable="false"/>
- <mx:DataGridColumn headerText="账号" dataField="username" editable="true"/>
- <mx:DataGridColumn headerText="密码" dataField="password" editable="true"/>
- <mx:DataGridColumn headerText="修改" width="50" editable="false" >
- <mx:itemRenderer>
- <fx:Component>
- <mx:LinkButton toolTip="修改" click="outerDocument.updataUser(event)" icon="@Embed('/image/update.gif')">
- </mx:LinkButton>
- </fx:Component>
- </mx:itemRenderer>
- </mx:DataGridColumn>
- <mx:DataGridColumn headerText="删除" width="50" editable="false" >
- <mx:itemRenderer>
- <fx:Component>
- <mx:LinkButton toolTip="删除" click="outerDocument.deleteUser(event)" icon="@Embed('/image/delete.gif')">
- </mx:LinkButton>
- </fx:Component>
- </mx:itemRenderer>
- </mx:DataGridColumn>
- </locdg:columns>
- </locdg:DoubleClickDataGrid>
- <s:Button x="491" y="189" label="取数 据" click="click_handler(event)" />
- <s:RichText x="606" y="189" id="info" text="点击按钮取数据"/>
- <mx:Form x="163" y="72" borderStyle="solid" borderVisible="true">
- <mx:FormItem label="用户名" borderStyle="solid" borderVisible="true">
- <s:TextInput id="username" />
- </mx:FormItem>
- <mx:FormItem label="密 码" borderStyle="solid" borderVisible="true">
- <s:TextInput id="password"/>
- </mx:FormItem>
- </mx:Form>
- <s:Button x="444" y="100" label="添 加" click="adduser_handler(event)"/>
- <s:RichText x="544" y="100" id="addinfo" text="请添加"/>
- </s:Application>