package org.data { import flash.data.*; import flash.events.EventDispatcher; import flash.events.SQLErrorEvent; import flash.events.SQLEvent; import flash.filesystem.*; import mx.controls.*; import org.event.SQLDataEvent; public class SQLData extends EventDispatcher { private var conn:SQLConnection; private var sqlStat:SQLStatement; public function SQLData() { } public function open(){ //建立一个连接 conn = new SQLConnection(); //监听事件 conn.addEventListener(SQLEvent.OPEN, openHandler); conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); //获取数据库路径 var dbFile:File = File.applicationStorageDirectory.resolvePath("e://wakao123/joke.db"); //打开数据库 conn.open(dbFile); } //插入操作 public function add(period,numbers):void{ try{ sqlStat.text = "Insert into sms(period,numbers) values('" +period+"','"+numbers+"')"; sqlStat.execute(); }catch(e:Error){ var event:SQLDataEvent=new SQLDataEvent(SQLDataEvent.SKIP) this.dispatchEvent(event) } } //删除操作 public function del(id):void{ sqlStat.text = "delete from sms where empId='" + id + "'"; sqlStat.execute(); } //修改记录 public function updata(period,numbers,id){ sqlStat.text = " update sms set period='"+period+ "',numbers='"+numbers+ "' where empId='" + id + "'"; sqlStat.execute(); } //创建表 private function createTable(){ var sql:String ="CREATE TABLE IF NOT EXISTS sms (" + " empId INTEGER PRIMARY KEY AUTOINCREMENT, " + " period TEXT, " + " numbers TEXT " + ")"; sqlStat.text = sql; sqlStat.execute(); } //增加新字段 private function addNewField(keyword:String){ var sql:String ="ALTER TABLE 'sms' ADD '"+keyword+"' TEXT" sqlStat.text = sql; sqlStat.execute(); } //获取数据函数 private function getResult():void{ sqlStat.text = "SELECT * FROM sms" sqlStat.execute(); } //去重复 public function delRepeat(){ sqlStat.text ="delete from sms where empId not in(select max(empId) from sms group by period having count(period)>=1)"; sqlStat.execute(); } //侦听事件 private function openHandler(e:SQLEvent){ //初始化sqlStatement对象,用于添加,删除等操作 sqlStat = new SQLStatement(); sqlStat.sqlConnection = conn; sqlStat.addEventListener(SQLEvent.RESULT, statResult); sqlStat.addEventListener(SQLErrorEvent.ERROR, createError); createTable() // addNewField() var event:SQLDataEvent=new SQLDataEvent(SQLDataEvent.SQLOPEN) this.dispatchEvent(event) } private function statResult(e:SQLEvent){ var sqlresult:SQLResult = sqlStat.getResult(); if(sqlresult.data == null){ getResult(); return; } var event:SQLDataEvent=new SQLDataEvent(SQLDataEvent.SQLUPDATA) event.data= sqlresult.data this.dispatchEvent(event) } private function errorHandler(e:SQLErrorEvent){ Alert.show(e.error.message) } private function createError(e:SQLErrorEvent){ Alert.show(e.error.message) } } } |