• flex与java实现增删改查


    用的是MySQL数据库。

    1,建一个userdb库,再建userinfo表,字 段:id(int),username(varchar),password(varchar)。

    1. create database userdb;  
    2. use userdb;  
    3. create table userinfo(  
    4. id int(10) not null auto_increment,  
    5. username varchar(20),  
    6. password varchar(20),  
    7. primary key(id));  

    2,DBConnection.java

    1. package com.datainfo;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.DriverManager;  
    5. import java.sql.SQLException;  
    6.   
    7. public class DBConnection {  
    8.     public static Connection getConnection() throws ClassNotFoundException,  
    9.             SQLException {  
    10.         Connection conn = null;  
    11.         String driver = "com.mysql.jdbc.Driver";  
    12.         String url = "jdbc:mysql://localhost:3306/userdb";  
    13.         String username = "root";  
    14.         String password = "mysql";  
    15.         Class.forName(driver);  
    16.         conn = DriverManager.getConnection(url, username, password);  
    17.         return conn;  
    18.     }  
    19. }  

    3,User.java

    1. package com.datainfo;  
    2.   
    3. public class User {  
    4.     private int id;  
    5.     private String username;  
    6.     private String password;  
    7.   
    8.     public User() {  
    9.           
    10.     }  
    11.   
    12.     /** 
    13.      * @return the id 
    14.      */  
    15.     public int getId() {  
    16.         return id;  
    17.     }  
    18.   
    19.     /** 
    20.      * @param id 
    21.      *            the id to set 
    22.      */  
    23.     public void setId(int id) {  
    24.         this.id = id;  
    25.     }  
    26.   
    27.     /** 
    28.      * @return the username 
    29.      */  
    30.     public String getUsername() {  
    31.         return username;  
    32.     }  
    33.   
    34.     /** 
    35.      * @param username 
    36.      *            the username to set 
    37.      */  
    38.     public void setUsername(String username) {  
    39.         this.username = username;  
    40.     }  
    41.   
    42.     /** 
    43.      * @return the password 
    44.      */  
    45.     public String getPassword() {  
    46.         return password;  
    47.     }  
    48.   
    49.     /** 
    50.      * @param password 
    51.      *            the password to set 
    52.      */  
    53.     public void setPassword(String password) {  
    54.         this.password = password;  
    55.     }  
    56. }  

    4,UserDAO.java

    1. package com.datainfo;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.PreparedStatement;  
    5. import java.sql.ResultSet;  
    6. import java.sql.SQLException;  
    7. import java.sql.Statement;  
    8. import java.util.ArrayList;  
    9.   
    10. import com.datainfo.DBConnection;  
    11.   
    12. public class UserDAO {  
    13.     public ArrayList getUserList() throws ClassNotFoundException, SQLException {  
    14.         Connection conn = DBConnection.getConnection();  
    15.         Statement stmt = conn.createStatement();  
    16.         ResultSet rs = stmt.executeQuery("select * from userinfo");  
    17.         ArrayList userList = null;  
    18.         try {  
    19.             userList = new ArrayList();  
    20.             while (rs.next()) {  
    21.                 User user = new User();  
    22.                 user.setId(rs.getInt("id"));  
    23.                 user.setUsername(rs.getString("username"));  
    24.                 user.setPassword(rs.getString("password"));  
    25.                 userList.add(user);  
    26.             }  
    27.             rs.close();  
    28.             stmt.close();  
    29.             conn.close();  
    30.         } catch (Exception e) {  
    31.             // TODO Auto-generated catch block  
    32.             e.printStackTrace();  
    33.         }  
    34.         return userList;  
    35.     }  
    36.   
    37.     public void addUser(User user) throws ClassNotFoundException, SQLException {  
    38.         Connection conn = DBConnection.getConnection();  
    39.         String sql = "insert into userinfo (username,password) values (?,?)";  
    40.         try {  
    41.             PreparedStatement pstmt = conn.prepareStatement(sql);  
    42.             pstmt.setString(1, user.getUsername());  
    43.             pstmt.setString(2, user.getPassword());  
    44.             pstmt.executeUpdate();  
    45.             pstmt.close();  
    46.             conn.close();  
    47.         } catch (Exception e) {  
    48.             // TODO Auto-generated catch block  
    49.             e.printStackTrace();  
    50.         }  
    51.     }  
    52.   
    53.     public void updataUser(User user) throws ClassNotFoundException,  
    54.             SQLException {  
    55.         Connection conn = DBConnection.getConnection();  
    56.         String sql = "update userinfo set username=?,password=? where id=?";  
    57.         try {  
    58.             PreparedStatement pstmt = conn.prepareStatement(sql);  
    59.             pstmt.setString(1, user.getUsername());  
    60.             pstmt.setString(2, user.getPassword());  
    61.             pstmt.setInt(3, user.getId());  
    62.             pstmt.executeUpdate();  
    63.             pstmt.close();  
    64.             conn.close();  
    65.         } catch (Exception e) {  
    66.             // TODO Auto-generated catch block  
    67.             e.printStackTrace();  
    68.         }  
    69.     }  
    70.   
    71.     public void deleteUser(User user) throws ClassNotFoundException,  
    72.             SQLException {  
    73.         Connection conn = DBConnection.getConnection();  
    74.         String sql = "delete from userinfo where id =?";  
    75.         try {  
    76.             PreparedStatement pstmt = conn.prepareStatement(sql);  
    77.             pstmt.setInt(1, user.getId());  
    78.             pstmt.executeUpdate();  
    79.             pstmt.close();  
    80.             conn.close();  
    81.         } catch (Exception e) {  
    82.             // TODO Auto-generated catch block  
    83.             e.printStackTrace();  
    84.         }  
    85.     }  
    86. }  

    5,配置文件remoting-config.xml

    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <service id="remoting-service" class="flex.messaging.services.RemotingService">  
    3.   
    4.     <adapters>  
    5.         <adapter-definition id="java-object"  
    6.             class="flex.messaging.services.remoting.adapters.JavaAdapter"  
    7.             default="true" />  
    8.     </adapters>  
    9.   
    10.     <default-channels>  
    11.         <channel ref="my-amf" />  
    12.     </default-channels>  
    13.   
    14.     <destination id="userDao">  
    15.         <properties>  
    16.             <source>com.datainfo.UserDAO</source>  
    17.         </properties>  
    18.     </destination>  
    19. </service>  

    6,以下是flex端,UserFlex.as

    1. package com.flex  
    2. {  
    3.     [Bindable]  
    4.     [RemoteClass(alias="com.datainfo.User")]  
    5.     public class UserFlex  
    6.     {  
    7. //      public function UserFlex{  
    8. //            
    9. //      }  
    10.         public var id:int;  
    11.         public var username:String;  
    12.         public var password:String;  
    13. //      如果用private,就需要写上get/set  
    14. //        
    15. //      public function get id():int{  
    16. //          return this.id;  
    17. //      }  
    18. //      public function set id():int{  
    19. //          this.id = id;  
    20. //      }  
    21. //        
    22. //      public function get username():String{  
    23. //          return this.username;  
    24. //      }  
    25. //      public function set username():String{  
    26. //          this.username = username;  
    27. //      }  
    28. //        
    29. //      public function get password():String{  
    30. //          return this.password;  
    31. //      }  
    32. //      public function set password():String{  
    33. //          this.password = password;  
    34. //      }  
    35.     }  
    36. }  

    7,自定义的DataGrid组件,用以双击修改数据DoubleClickDataGrid.as

    1. package com.flex  
    2. {  
    3.     import flash.events.MouseEvent;  
    4.     import mx.controls.DataGrid;  
    5.     import mx.controls.dataGridClasses.DataGridColumn;  
    6.     import mx.controls.listClasses.IDropInListItemRenderer;  
    7.     import mx.controls.listClasses.IListItemRenderer;  
    8.     import mx.core.EventPriority;  
    9.     import mx.events.DataGridEvent;  
    10.       
    11.       
    12.     public class DoubleClickDataGrid extends DataGrid  
    13.     {  
    14.         public function DoubleClickDataGrid()  
    15.         {  
    16.             //TODO: implement function  
    17.             super();  
    18.             doubleClickEnabled = true;  
    19.         }  
    20.         override protected function mouseDoubleClickHandler(event:MouseEvent):void  
    21.         {  
    22.             var dataGridEvent:DataGridEvent;  
    23.             var r:IListItemRenderer;  
    24.             var dgColumn:DataGridColumn;  
    25.               
    26.             r = mouseEventToItemRenderer(event);  
    27.             if (r && r != itemEditorInstance)  
    28.             {  
    29.                 var dilr:IDropInListItemRenderer = IDropInListItemRenderer(r);  
    30.                 if (columns[dilr.listData.columnIndex].editable)  
    31.                 {  
    32.                     dgColumn = columns[dilr.listData.columnIndex];  
    33.                     dataGridEvent = new DataGridEvent(DataGridEvent.ITEM_EDIT_BEGINNING, false, true);  
    34.                     // ITEM_EDIT events are cancelable  
    35.                       
    36.                     dataGridEvent.columnIndex = dilr.listData.columnIndex;  
    37.                     dataGridEvent.dataField = dgColumn.dataField;  
    38.                     dataGridEvent.rowIndex = dilr.listData.rowIndex + verticalScrollPosition;  
    39.                     dataGridEvent.itemRenderer = r;  
    40.                     dispatchEvent(dataGridEvent);  
    41.                 }  
    42.             }  
    43.               
    44.             super.mouseDoubleClickHandler(event);  
    45.         }  
    46.           
    47.         override protected function mouseUpHandler(event:MouseEvent):void  
    48.         {  
    49.             var r:IListItemRenderer;  
    50.             var dgColumn:DataGridColumn;  
    51.               
    52.             r = mouseEventToItemRenderer(event);  
    53.             if (r)  
    54.             {  
    55.                 var dilr:IDropInListItemRenderer = IDropInListItemRenderer(r);  
    56.                 if (columns[dilr.listData.columnIndex].editable)  
    57.                 {  
    58.                     dgColumn = columns[dilr.listData.columnIndex];  
    59.                     dgColumn.editable = false;  
    60.                 }  
    61.             }  
    62.               
    63.             super.mouseUpHandler(event);  
    64.               
    65.             if (dgColumn)  
    66.                 dgColumn.editable = true;  
    67.         }  
    68.           
    69.     }  
    70. }  

    8,页面显示,testflex.mxml

    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"   
    3.                xmlns:s="library://ns.adobe.com/flex/spark"   
    4.                xmlns:mx="library://ns.adobe.com/flex/mx"   
    5.                xmlns:locdg="com.flex.*"  
    6.                creationComplete="initApp()"  
    7.                minWidth="955" minHeight="600">  
    8.     <fx:Declarations>  
    9.         <!-- 将非可视元素(例如服务、值对象)放在此处 -->  
    10.         <s:RemoteObject id="userdata" destination="userDao" result="onResult(event)" fault="onFault(event)" />  
    11.         <!--<s:method name="getUserList" result="onResult(event)" fault="onFault(event)" />-->  
    12.         <s:RemoteObject id="adduserdata" destination="userDao" result="addResult(event)" fault="addFault(event)" />  
    13.         <s:RemoteObject id="updatauserdata" destination="userDao" result="updataResult(event)" fault="updataFault(event)" />  
    14.         <s:RemoteObject id="deleteuserdata" destination="userDao" result="deleteResult(event)" fault="deleteFault(event)" />  
    15.     </fx:Declarations>  
    16.     <fx:Script>  
    17.         <!--[CDATA[  
    18.             import com.flex.UserFlex;  
    19.               
    20.             import mx.collections.ArrayCollection;  
    21.             import mx.controls.Alert;  
    22.             import mx.managers.CursorManager;  
    23.             import mx.rpc.events.FaultEvent;  
    24.             import mx.rpc.events.ResultEvent;  
    25.               
    26.             public var userFlex:UserFlex = new UserFlex();  
    27.             public var result:Object = new Object();  
    28.             [Bindable]  
    29.             public var users:ArrayCollection = new ArrayCollection();  
    30.               
    31.             public function initApp():void{  
    32. //              userdata.getUserList();  
    33.             }  
    34.               
    35.             public function click_handler(event:Event):void{  
    36.                 CursorManager.setBusyCursor();  
    37.                 info.text = "正在查 询...";  
    38.                 userdata.getUserList();  
    39.             }  
    40.             public function adduser_handler(event:Event):void{  
    41.                 if(username.text != "" && password.text != ""){  
    42.                     CursorManager.setBusyCursor();  
    43.                     addinfo.text = "正在添加...";  
    44.                     userFlex.username = username.text;  
    45.                     userFlex.password = password.text;  
    46.                     adduserdata.addUser(userFlex);  
    47.                 }else{  
    48.                     addinfo.text = " 用户名和密码不能为空";  
    49.                 }  
    50.             }  
    51.             public function updataUser(event:Event):void{  
    52.                 if(userlist.selectedItem.username != "" && userlist.selectedItem.password != ""){  
    53.                     CursorManager.setBusyCursor();  
    54.                     info.text = "正在 更新...";  
    55.                     userFlex.id = userlist.selectedItem.id;  
    56.                     userFlex.username = userlist.selectedItem.username;  
    57.                     userFlex.password = userlist.selectedItem.password;  
    58.                     updatauserdata.updataUser(userFlex);  
    59.                 }  
    60. //              Alert.show("确认修改?");  
    61.             }  
    62.             public function deleteUser(event:Event):void{  
    63.                 CursorManager.setBusyCursor();  
    64.                 info.text = "正在正在删 除...";  
    65.                 userFlex.id = userlist.selectedItem.id;  
    66.                 deleteuserdata.deleteUser(userFlex);  
    67.             }  
    68.               
    69.             public function onResult(event:ResultEvent):void{  
    70.                 users = event.result as ArrayCollection;  
    71.                 CursorManager.removeBusyCursor();  
    72.                 if(users.length==0){  
    73.                     info.text="取数据成功,为空";  
    74.                 }else{  
    75.                     info.text = " 取数据成功";  
    76.                 }  
    77.             }  
    78.             public function onFault(event:FaultEvent):void{  
    79.                 CursorManager.removeBusyCursor();  
    80.                 info.text="取数据失败";  
    81.             }  
    82.             public function addResult(event:ResultEvent):void{  
    83.                 CursorManager.removeBusyCursor();  
    84.                 userdata.getUserList();  
    85.                 username.text = "";  
    86.                 password.text = "";  
    87.                 addinfo.text = " 添加成功";  
    88.                 //              info.text = "取数据成功";  
    89.             }  
    90.             public function addFault(event:FaultEvent):void{  
    91.                 CursorManager.removeBusyCursor();  
    92.                 addinfo.text="添加失败";  
    93.             }  
    94.             public function updataResult(event:ResultEvent):void{  
    95.                 CursorManager.removeBusyCursor();  
    96.                 userdata.getUserList();  
    97.                 info.text = "修改数 据成功";  
    98.             }  
    99.             public function updataFault(event:FaultEvent):void{  
    100.                 CursorManager.removeBusyCursor();  
    101.                 info.text="修改数据失 败";  
    102.             }  
    103.             public function deleteResult(event:ResultEvent):void{  
    104.                 CursorManager.removeBusyCursor();  
    105.                 userdata.getUserList();  
    106.                 info.text = "刪除数据成 功";  
    107.             }  
    108.             public function deleteFault(event:FaultEvent):void{  
    109.                 CursorManager.removeBusyCursor();  
    110.                 info.text="刪除数据失败";  
    111.             }  
    112.         ]]-->  
    113.     </fx:Script>  
    114.     <locdg:DoubleClickDataGrid x="61" y="189" id="userlist" dataProvider="{users}" editable="true">  
    115.         <locdg:columns>  
    116.             <mx:DataGridColumn headerText="ID号" dataField="id" editable="false"/>  
    117.             <mx:DataGridColumn headerText="账号" dataField="username" editable="true"/>  
    118.             <mx:DataGridColumn headerText="密码" dataField="password" editable="true"/>  
    119.             <mx:DataGridColumn headerText="修改" width="50" editable="false" >  
    120.                 <mx:itemRenderer>  
    121.                     <fx:Component>  
    122.                         <mx:LinkButton toolTip="修改" click="outerDocument.updataUser(event)" icon="@Embed('/image/update.gif')">  
    123.                         </mx:LinkButton>  
    124.                     </fx:Component>  
    125.                 </mx:itemRenderer>  
    126.             </mx:DataGridColumn>  
    127.             <mx:DataGridColumn headerText="删除" width="50" editable="false" >  
    128.                 <mx:itemRenderer>  
    129.                     <fx:Component>  
    130.                         <mx:LinkButton toolTip="删除" click="outerDocument.deleteUser(event)" icon="@Embed('/image/delete.gif')">     
    131.                         </mx:LinkButton>  
    132.                     </fx:Component>  
    133.                 </mx:itemRenderer>  
    134.             </mx:DataGridColumn>  
    135.         </locdg:columns>  
    136.     </locdg:DoubleClickDataGrid>  
    137.     <s:Button x="491" y="189" label="取数 据" click="click_handler(event)" />  
    138.     <s:RichText x="606" y="189" id="info" text="点击按钮取数据"/>  
    139.     <mx:Form x="163" y="72" borderStyle="solid" borderVisible="true">  
    140.         <mx:FormItem label="用户名" borderStyle="solid" borderVisible="true">  
    141.             <s:TextInput id="username" />  
    142.         </mx:FormItem>  
    143.         <mx:FormItem label="密 码" borderStyle="solid" borderVisible="true">  
    144.             <s:TextInput id="password"/>  
    145.         </mx:FormItem>  
    146.     </mx:Form>  
    147.     <s:Button x="444" y="100" label="添 加" click="adduser_handler(event)"/>  
    148.     <s:RichText x="544" y="100" id="addinfo" text="请添加"/>  
    149. </s:Application>  

    源码下载

  • 相关阅读:
    键值表
    CRC校验方法
    extern 使用
    编码格式简介(ANSI、GBK、GB2312、UTF-8、GB18030和 UNICODE)
    学习积累
    二分查找写法
    生活技术常识
    JAVA实例
    JAVA_Sprint学习(一)
    手把手使用Git?
  • 原文地址:https://www.cnblogs.com/nianshi/p/1732440.html
Copyright © 2020-2023  润新知