使用lua脚本函数在手机上编写一个日历形式的记事本,涉及到一些常用的lua函数的使用,使用sqlite数据库进行本地数据保存。
使用app:
1.代码手册(帮我查询一些函数的使用,知识点很全面)
2.Mlua(lua解析器,在上面完成代码编写和运行打包)
由于新手上路,所有代码都在一个页面完成,有点混乱
require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
import 'android.graphics.*'
import 'android.graphics.RectF'
import 'android.graphics.Paint'
import 'android.graphics.drawable.shapes.RoundRectShape'
import 'android.graphics.drawable.ShapeDrawable'
--[[==============;;;=数据库操作==;;=============]]
--导入包
import "android.database.sqlite.*"
dts={}--记事数据
--字符串替换
function str(s)
--s=string.gsub(s,"/","//")
s=string.gsub(s,"'","''")
--s=string.gsub(s,"&","/&")
--s=string.gsub(s,"_","/_")
return s
end
tbname="tb_note"--表名
dbname="notes.db"
dbpath=this.getLuaDir().."/"..dbname--存放路径
--打开数据库(没有自动创建)
db = SQLiteDatabase.openOrCreateDatabase(dbpath,MODE_PRIVATE, nil);
--execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句
function exec(sql)
db.execSQL(sql);
end
--rawQuery()方法用于执行select语句。
function raw(sql,text)
cursor=db.rawQuery(sql,text)
end
--创建数据库表
function createdbtable()
--查询表是否存在
local sql="select count(*) from sqlite_master where type='table' and name = '"..tbname.."'"
if pcall(raw,sql,nil) then
cursor.moveToNext()
local nn=cursor.getInt(0)
if nn < 1 then
sql="create table "..tbname.."(id integer primary key,t_data text,t_date smalldatetime)"
if pcall(exec,sql) then
return 1--创建成功
else
return 0--创建失败
end
else
return -1--表已存在
end
end
end
--添加数据
function adddata(da,de)
if pcall(exec,"insert into "..tbname.." (t_data,t_date) values('"..str(da).."','"..de.."')") then
return true--添加成功
else
return false--添加失败
end
end
--删除数据
function deldata(d)
if pcall(exec,"delete from "..tbname.." where id="..d) then
return true--成功
else
return false--失败
end
end
--更新数据
function updata(da,d)
--根据id更新数据,不更新创建时间
if pcall(exec,"update "..tbname.." set t_data='"..str(da).."' where id="..d) then
return true--成功
else
return false--失败
end
end
--查询数库
function seldata(sql)
dts={}
if pcall(raw,sql,nil) then
while (cursor.moveToNext()) do
local tid = cursor.getInt(0);
local tda = cursor.getString(1);
local tde = cursor.getString(2);
table.insert(dts,{id=tid,date=tde,data=tda});
end
cursor.close()
else
--print("查询失败")
end
end
--查询所有
function selall()
seldata("select * from "..tbname)
end
--[[==============;;;=数据库操作==;;=============]]
colorlist={0xffFFEBEE,0xFfEDE7F6,0xFfE1F5FE,0xffE8F5E9,0xffFFFDE7,0xffFBE9E7,0xffECEFF1,0xffF3E5F5,0xffE3F2FD,0xffE0F2F1,0xffF9FBE7,0xffFFF3E0,0xffFCE4EC}
function gettitle(n)
if n==1 then
return "日"
end
if n==2 then
return "一"
end
if n==3 then
return "二"
end
if n==4 then
return "三"
end
if n==5 then
return "四"
end
if n==6 then
return "五"
end
if n==7 then
return "六"
end
return ""
end
function kong(t)
local t3={
LinearLayout;
Orientation='vertical';
layout_width=wd..'px';
{
TextView;
layout_width='fill';
layout_height='38dp';
Gravity='center';
textColor='#000000';
text="";
textSize='18sp';
background='#F5F5F5';
--background='#EEEEEE';
--[[
BackgroundDrawable=LuaDrawable(function(canvas,paint,draw)
paint.setColor(0xff000000)
paint.setStyle(Paint.Style.STROKE)
paint.setStrokeWidth(2)
canvas.drawRoundRect(RectF(draw.getBounds()),0,0,paint)
end);
]]
};
}
table.insert(t,t3)
end
--设置每格的宽度,根据屏幕宽度
wd=(activity.getWidth()-20)/7
--自定义字符串分隔符获取数组
function string.split(input, delimiter)
input = tostring(input)
delimiter = tostring(delimiter)
if (delimiter=='') then return false end
local pos,arr = 0, {}
-- for each divider found
for st,sp in function() return string.find(input, delimiter, pos, true) end do
table.insert(arr, string.sub(input, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(input, pos))
return arr
end
--获取年,月,第一天是周几
function a1(y,m)
local dt=os.date("*t",os.time({year=y,month=m,day="1"}))
return (dt["wday"]-1)
end
--获取年,月有多少天
function a2(y,m)
local ml=os.difftime(os.time({year=a3(y,m)["year"],month=a3(y,m)["month"],day="1"}),os.time({year=y,month=m,day="1"}))
ml=ml/60/60/24
return math.floor(ml)
end
--获取年,月上一月份
function a4(y,m)
local o=os.time({year=y,month=m,day="1"})-(60*60*24*28)
local cd=os.date("*t",o)
return {year=cd["year"],month=cd["month"]}
end
--获取年,月下一月份
function a3(y,m)
local o=os.time({year=y,month=m,day="1"})+(60*60*24*31)
local cd=os.date("*t",o)
return {year=cd["year"],month=cd["month"]}
end
--把时间字符串转换为时间
function gtd(s)
local ss=string.split(s,"-")
return os.date("*t",os.time({year=ss[1],month=ss[2],day=ss[3]}))
end
--截取字符串,返回少量字符串,其他显示...
function subs(s,n)--字符串,显示多少个字符
if string.len(s) > n then
s=string.gsub(s,"\n","")
s=string.gsub(s," ","")
return string.sub(s,1,n).."..."
else
return s
end
end
---------
--查询每月的数据
function selmonth(y,m)--年,月
local dd=a2(y,m)--本月有多少天
local fd=y.."-"..m.."-01"--第一天
local ld=y.."-"..m.."-"..dd--最后一天
--时间必须是0000-00-00格式的
fd=os.date("%Y-%m-%d",os.time(gtd(fd)))
ld=os.date("%Y-%m-%d",os.time(gtd(ld)))
local sql="select * from "..tbname.." where t_date>='"..fd.."' and t_date<='"..ld.."'"
seldata(sql)
end
--查询每一天的数据
function selday(y,m,d)--年,月,日
d=y.."-"..m.."-"..d
d=os.date("%Y-%m-%d",os.time(gtd(d)))
local sql="select * from "..tbname.." where t_date='"..d.."'"
seldata(sql)
end
--selmonth("2020","03")
--selday("2020","3","24")
lo=nil--选择上一个日期
bcc1,bcc2,bcc3,bcc4="#FFFDE7","#FFF59D","#FFCDD2","#F44336"--代表平常,今天,有记事,选择后背景色
cdt=os.date("*t",os.time())
cyear=cdt["year"]
cmonth=cdt["month"]
w=a1(cyear,cmonth)--周几
z,n=a2(cyear,cmonth),7--有31天,7天一周
m=math.ceil((z+w)/n)
cyear,cmonth,cday="","",""--当前年月日
--获取背景色,根据不同的情况获取背景色
function getbkc()
--判断今天
local sy=os.date("*t",os.time())
if cyear==sy["year"] and cmonth==sy["month"] and cday==sy["day"] then
return bcc2
end-----
--判断是否有记事记录
if dts~=nil then
for i,v in pairs(dts) do
local sy=gtd(v["date"])
if cyear==sy["year"] and cmonth==sy["month"] and cday==sy["day"] then
return bcc3
end
end
end
return bcc1
end
--显示今天
function jt()
local dt=os.date("*t",os.time())
cyear=dt["year"]
cmonth=dt["month"]
w=a1(cyear,cmonth)
z=a2(cyear,cmonth)
m=math.ceil((z+w)/n)
--selmonth(cyear,cmonth)--查询当月数据
--selday(cyear,cmonth,dt["day"])--查询今天的数据
rili()--更新数据
end
--显示上一月
function st()
local sy=a4(cyear,cmonth)
cyear=sy["year"]
cmonth=sy["month"]
w=a1(cyear,cmonth)
z=a2(cyear,cmonth)
m=math.ceil((z+w)/n)
--selmonth(cyear,cmonth)--查询当月数据
rili()
end
--显示下一月
function xt()
local sy=a3(cyear,cmonth)
cyear=sy["year"]
cmonth=sy["month"]
w=a1(cyear,cmonth)
z=a2(cyear,cmonth)
m=math.ceil((z+w)/n)
--selmonth(cyear,cmonth)--查询当月数据
rili()
end
--[[=========================
日历页面
]]
function rili()
selmonth(cyear,cmonth)--查询当月数据
t={LinearLayout;
orientation="vertical";
layout_width='100%w';
padding="10px";
}
--表头
local t1={
LinearLayout;
Orientation='horizontal';
layout_width='100%w';
layout_marginTop="8dp";
}
for j=1,n do
local txt=gettitle(j)
local t2={
LinearLayout;
Orientation='horizontal';
layout_width=wd..'px';
background='#42A5F5';
{
TextView;
layout_width='fill';
layout_height='48dp';
Gravity='center';
textColor='#ffffff';
text=txt;
textSize='18sp';
};
};
table.insert(t1,t2)
end
table.insert(t,t1)
--表体
for i=1,m do
local t1={
LinearLayout;
Orientation='horizontal';
layout_width='fill';
}
for j=1,n do
local tmp=n*i+j-n-w
cday=tmp--当前日期赋值
if tmp > z then
kong(t1)
continue
--break
end
if i==1 and j <= w then
kong(t1)
continue
end
local t2={
LinearLayout;
Orientation='vertical';
layout_width=wd..'px';
background=getbkc();--动态获取背景色
{
TextView;
layout_width='fill';
layout_height='38dp';
Gravity='center';
textColor='#000000';
text=tmp.."";
textSize='18sp';
onClick=function(o)
--实现让点击日期时,当前日期变色,上一个日期恢复颜色
if lo ~= nil then
lo.setTextColor(Color.parseColor('#000000'))
end
o.setTextColor(Color.parseColor(bcc4))
lo=o--赋值给上一个控件
cday=tmp--当前选择日期赋值
--更新数据
--selday(cyear,cmonth,o.text)
--rili()
end;
};
};
table.insert(t1,t2)
end
table.insert(t,t1)
end
local t2={
LinearLayout;
Orientation='horizontal';
layout_width="fill";
background='#EEEEEE';
padding="10px";
{
TextView;
layout_width='33%w';
layout_height='38dp';
Gravity='left';
textColor='#FF9800';
text="上一月";
textSize='16sp';
onClick=function()
st()
--rili()
end;
};
{
TextView;
layout_width='33%w';
layout_height='38dp';
Gravity='center';
textColor='#2196F3';
text=cyear.."-"..cmonth.." [今]";
textSize='16sp';
onClick=function()
jt()
--rili()
end;
};
{
TextView;
layout_width='30%w';
layout_height='38dp';
Gravity='right';
textColor='#FF9800';
text="下一月";
textSize='16sp';
onClick=function()
xt()
--rili()
end;
};
};
local t3={
ListView;--列表视图
layout_width='fill';
layout_height='fill';
DividerHeight='1';--设置分隔线宽度,0表示无分隔
id="rllist";
};
table.insert(t,t2)
table.insert(t,t3)
--print("test")
activity.setContentView(loadlayout(t))
local rlitem={
LinearLayout,
orientation="horizontal",
layout_width="fill",
{
TextView,
id="rlitemTXT",
layout_margin="15dp",
layout_width="80%w"
},
{
TextView,
id="delTXT",
layout_margin="15dp",
layout_width="20%w",
TextColor="#F44336";
layout_height='fill';
text="删除",
},
}
local dtt={}
--创建适配器,将数据表和自定义视图添加进适配器
adpp=LuaAdapter(activity,dtt,rlitem)--dts是数据
for i,v in pairs(dts) do--把dts数据集合中的数据添加到list数据组中
table.insert(dtt,{
rlitemTXT={
Text=v["date"].."\t\t"..subs(v["data"],38),
Tag=v["id"];
onClick=function(o)
--print(o.Tag)
addbiji(o.Tag)
end;
},
delTXT={
--Text=v["date"].."\t\t"..subs(v["data"],38);
Tag=v["id"];
onClick=function(o)
AlertDialog.Builder(this)
.setTitle("删除提示")
.setMessage("你是否要删除这条笔记?")
.setPositiveButton("删除",{
onClick=function(v)
--print("删除"..o.Tag)
deldata(o.Tag)
rili()
end
})
--.setNeutralButton("中立",nil)
.setNegativeButton("点错了",nil)
.show()
end;
},
})
end
--为list设置适配器
rllist.Adapter=adpp
end
editxt=""
ediid=0
ccpage=nil--当前页面
--添加笔记
function addbiji(idd)--id,如果为0则添加
-- print(idd)
idd=tonumber(idd)
if idd<=0 then--添加
editxt=""
ediid=0
else--修改
for i,v in pairs(dts) do
if v["id"]==idd then
editxt=v["data"]
ediid=idd
break
end
end
end
adp={
LinearLayout;
orientation="vertical";
layout_width='100%w';
padding="10px";
{
LinearLayout;
orientation="horizontal";
Gravity='right';
layout_width='100%w';
padding="10px";
{
Button;
layout_marginBottom="16dp";
layout_width="50dp";
layout_height="38dp";
text="取消";
id="addbnt";
textSize="12dp";
layout_marginLeft="16dp";
layout_marginRight="16dp";
background="#009688";
textColor="#ffffff";
onClick=ccpage;--当前访问的页面初始化方法
};
{
Button;
layout_marginBottom="16dp";
layout_width="50dp";
layout_height="38dp";
text="保存";
id="quxiaobnt";
textSize="12dp";
layout_marginLeft="16dp";
layout_marginRight="16dp";
background="#009688";
textColor="#ffffff";
onClick=function()
local str=edit.text
if tostring(ediid)=="0" then--添加
if str ~= "" then
adddata(str,os.date("%Y-%m-%d",os.time()))
end
else--修改
updata(str,ediid)
end
ccpage()--更新加载页面
end;
};
};
{
EditText;
layout_width="95%w";
id="edit";
background="#FFFDE7";
textSize="14dp";
layout_marginTop="6dp";
layout_marginLeft="16dp";
layout_marginRight="16dp";
inputType="textMultiLine";
textScaleX="1";
hint="在这里开始记录你的笔记吧~";
Tag=ediid;
text=editxt;
};
}
activity.setContentView(loadlayout(adp))
end
-------聊天界面
function dymoli(s)
local yy={
{"[date]",os.date("%Y-%m-%d %H:%M:%S",os.time())},
{"[cqname]","小茉莉"},
{"[father]","屏幕"},
{"[mother]","屏幕"},
{"[name]","主人"},
{"[height]","168cm"},
{"[weight]","48kg"},
{"[sex]","mm"},
{"[zodiac]","双鱼座"},
{"[blood]","O型"},
{"[school]","清华大学"},
{"[city1]","江苏省"},
{"[city1]","苏州市"},
}
for i,v in pairs(yy) do
s=string.gsub(s,"%"..v[1],v[2])
end
return s
end
function xy(a,b,c,d)
if tostring(a)=="200" then
--print(b)
vsedit.text=vsedit.text.."\r\n小茉莉: "..dymoli(b).."\r\n"
scrview.fullScroll(View.FOCUS_DOWN);
end
end
function char()
local adp={
LinearLayout;
orientation="vertical";
layout_width='100%w';
padding="10px";
{
LinearLayout;
orientation="horizontal";--horizontal
--Gravity='right';
layout_width='100%w';
padding="10px";
layout_marginTop="16dp";
layout_marginLeft="16dp";
layout_marginRight="16dp";
layout_marginBottom="16dp";
{
Button;
--layout_marginBottom="16dp";
layout_width="13%w";
layout_marginRight="16dp";
layout_height="36dp";
text="返回";
textSize="12dp";
background="#009688";
textColor="#ffffff";
onClick=function()
selall()
tt11()
end;
};
{
EditText;
layout_width="55%w";
id="esedit";
background="#FFFDE7";
textSize="14dp";
textScaleX="1";
text="";
};
{
Button;
--layout_marginBottom="16dp";
layout_width="13%w";
layout_marginLeft="16dp";
layout_height="36dp";
text="发送";
id="squxiaobnt";
textSize="12dp";
--layout_marginLeft="1dp";
--layout_marginRight="16dp";
background="#009688";
textColor="#ffffff";
onClick=function()
local str=esedit.text
if str~="" and string.len(str)>0 then
vsedit.text=vsedit.text.."\r\n我: "..str.."\r\n"
esedit.text=""
Http.get("http://i.itpk.cn/api.php?question="..str,xy)
end
end;
};
};
{
LinearLayout;
orientation="vertical";--horizontal
--Gravity='right';
layout_width='100%w';
--padding="10dp";
{
ScrollView;
layout_width="90%w";
layout_height="wrap_content";
id="scrview";
{
TextView;
id="vsedit";
textSize="14dp";
layout_marginTop="6dp";
layout_marginLeft="16dp";
layout_marginRight="16dp";
padding="10dp";
text="";
};
};
};
}
activity.setContentView(loadlayout(adp))
end
-------搜索界面
issearch=false
function searchpage()
local adp={
LinearLayout;
orientation="vertical";
layout_width='100%w';
padding="10px";
{
LinearLayout;
orientation="horizontal";--horizontal
--Gravity='right';
layout_width='100%w';
padding="10px";
{
EditText;
layout_width="70%w";
id="sedit";
background="#FFFDE7";
textSize="14dp";
layout_marginTop="6dp";
layout_marginLeft="16dp";
layout_marginRight="16dp";
inputType="textMultiLine";
textScaleX="1";
hint="搜索~";
Tag=ediid;
text="";
};
{
Button;
--layout_marginBottom="16dp";
layout_width="60dp";
layout_marginTop="6dp";
layout_height="36dp";
text="搜索";
id="quxiaobnt";
textSize="12dp";
layout_marginLeft="1dp";
--layout_marginRight="16dp";
background="#009688";
textColor="#ffffff";
onClick=function()
local str=sedit.text
if str~="" and string.len(str)>0 then
local sql="select * from "..tbname.." where t_data like '%"..str.."%'"
seldata(sql)
issearch=true
end
tt11()
end;
};
};
}
activity.setContentView(loadlayout(adp))
end
--[[=========================
加载页面
]]
function tt11()
if not issearch then
selall()
end
local scale = activity.getResources().getDisplayMetrics().scaledDensity
local pmk=(activity.getWidth() / scale + 0.5)--屏幕宽
local pmg=(activity.getHeight() / scale + 0.5)--屏幕高
local ggg=150
t11={
FrameLayout;
{
Button,
id="searchbnt",
background='#eeeeee';
--elevation="20dp",
text="Q";
layout_width="50dp";
layout_height="50dp";
layout_marginTop=(pmg-165-ggg).."dp";
layout_marginLeft=(pmk-55).."dp";
TextColor="#ff60c4ba";
TextSize="30";
padding="12";
onClick=function()
char()
end;
};
{
Button,
id="searchbnt",
background='#eeeeee';
--elevation="20dp",
text="?";
layout_width="50dp";
layout_height="50dp";
layout_marginTop=(pmg-110-ggg).."dp";
layout_marginLeft=(pmk-55).."dp";
TextColor="#ff60c4ba";
TextSize="30";
padding="12";
onClick=function()
issearch=false
searchpage()--char()
end;
};
{
Button,
id="fab",
background='#eeeeee';
--elevation="20dp",
text="+";
layout_width="50dp";
layout_height="50dp";
layout_marginTop=(pmg-55-ggg).."dp";
layout_marginLeft=(pmk-55).."dp";
TextColor="#ff60c4ba";
TextSize="30";
padding="12";
onClick=function()
addbiji(0)
end;
};
--------
--加载数据的列表识图
--------
{
ListView;--列表视图
layout_width='fill';
layout_height='fill';
DividerHeight='0';--设置分隔线宽度,0表示无分隔
id="dtlist";
};
}
--创建自定义项目视图,也就是一个文字视图。
item={
LinearLayout,
orientation="horizontal",
layout_width="fill",
--id="lstitem",
{
CardView;--卡片控件
id="card";--设置id
layout_margin='8dp';--卡片边距
layout_gravity='center';--子控件在父布局中的对齐方式
CardElevation='2dp';--卡片阴影
layout_width='fill';--卡片宽度
layout_height='fill';--卡片高度
radius='8dp';--卡片圆角
--CardBackgroundColor='#FFDDA767';--
{
LinearLayout,
orientation="horizontal",
layout_width="fill",
{
TextView,
id="itemTXT",
layout_margin="15dp",
layout_width="70%w",
},
{
LinearLayout,
orientation="horizontal",
layout_width="20%w",
gravity='right';
{
TextView,
id="delTXT",
layout_margin="15dp",
TextColor="#F44336";
text="删除",
},
},
},
},
}
activity.setContentView(loadlayout(t11))
dtt={}
--创建适配器,将数据表和自定义视图添加进适配器
adpp=LuaAdapter(activity,dtt,item)--dts是数据
for i,v in pairs(dts) do--把dts数据集合中的数据添加到list数据组中
table.insert(dtt,{
card={
CardBackgroundColor=colorlist[i%#colorlist], --表里用了取余算法,让颜色实现循环。
},
itemTXT={
--加载,多余的字显示。。。
Text=v["date"].."\t\t"..subs(v["data"],58);
Tag=v["id"];
onClick=function(o)
addbiji(o.Tag)
end;
},
delTXT={
Tag=v["id"];
onClick=function(o)
AlertDialog.Builder(this)
.setTitle("删除提示")
.setMessage("你是否要删除这条笔记?")
.setPositiveButton("删除",{
onClick=function(v)
deldata(o.Tag)--删除操作
tt11()
end
})
.setNegativeButton("点错了",nil)
.show()
end;
},
})
end
--为list设置适配器
dtlist.Adapter=adpp
end
function onCreate()
createdbtable()
--print("窗口创建")
jt()
tt11()
ccpage=tt11
--char()
end
--[[其他窗体事件
function main(...)
--...是newActivity传递过来的参数。
print("入口函数",...)
end
function onCreate()
print("窗口创建")
end
function onStart()
print("活动开始")
end
function onResume()
print("返回程序")
end
function onPause()
print("活动暂停")
end
function onStop()
print("活动停止")
end
function onDestroy()
print("程序已退出")
end
]]
--activity.setContentView(loadlayout(t))
--ActionBar返回按钮
--activity.ActionBar.setDisplayHomeAsUpEnabled(false)
--自定义返回按钮图标
--activity.ActionBar.setHomeAsUpIndicator(drawable)
import "android.text.SpannableString"
import "android.text.style.ForegroundColorSpan"
import "android.text.Spannable"
--sp = SpannableString("日历")
--sp.setSpan(ForegroundColorSpan(0xff1DA6DD),0,#sp,Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
--activity.ActionBar.setTitle(sp)
--菜单
function onCreateOptionsMenu(menu)
menu.add("退出")
end
function onOptionsItemSelected(item)
if item.Title~=nil then
if item.Title=="退出"
AlertDialog.Builder(this)
.setTitle("退出提示")
.setMessage("你是否要退出?")
.setPositiveButton("是",{onClick=function(v) os.exit() end})
.setNegativeButton("否",nil)
.show()
end
end
end
--ActionBar返回按钮
--activity.ActionBar.setDisplayHomeAsUpEnabled(false)
--自定义返回按钮图标
--activity.ActionBar.setHomeAsUpIndicator(drawable)
--Tab导航使用
import "android.app.ActionBar$TabListener"
actionBar=activity.ActionBar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab = actionBar.newTab().setText("笔记").setTabListener(TabListener({
onTabSelected=function()
--print"Tab1"
sp = SpannableString("笔记列表")
sp.setSpan(ForegroundColorSpan(0xff1DA6DD),0,#sp,Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
activity.ActionBar.setTitle(sp)
ccpage=tt11
tt11()
end}))
tab2=actionBar.newTab().setText("日历").setTabListener(TabListener({
onTabSelected=function()
--print"Tab2"
sp = SpannableString("日历列表")
sp.setSpan(ForegroundColorSpan(0xff1DA6DD),0,#sp,Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
activity.ActionBar.setTitle(sp)
ccpage=jt
jt()
end}))
actionBar.addTab(tab)
actionBar.addTab(tab2)
代码
在lua中sqlite使用代码
--[[
【常用SQL语句】
1.数据类型:
整型:int
字符:char(6)
varchar(24)
文本:text
布尔:bit
日期:smalldatetime
2.删除表:
drop table 表名
3.修改表:
alter table 表名 add 字段 类型
//加约束
alter table 表名 add constraint 约束
4.创建表:
create table 表名(
字段 类型 primary key,
字段 类型 default'值1' check(字段 in('值1','值2'))
)
//多个主键在最后面:
primary key(字段1,字段2)
//参照:
后面加:references 表名(字段)
//条件:
不为空:not null
唯一性:unique
//约束:
check(字段>=值 and 字段<=值)
check(字段 in('值1','值2'))
5.查询语句:
select * from 表名 where 条件语句
6.插入数据:
insert into 表名(字段列表) values(值列表)
7.更新语句:
update 表名 set 字段名 = 值 where 条件
8.删除语句:
delete from 表名 where 条件
9.分页查询:
select * from Account limit 3,5
(获取5条记录,跳过前面3条)
--一一一一一一一一一一一一一一一一一一一一
【常用SQL语句2】
1.子查询:
例:
select 学号,成绩 from xs_kc
where 课程号=(select 课程号 from kc where 课程名='计算机基础')
2.连接查询:
例:
select 学号,成绩 from xs_kc,kc
where xs_kc.课程号=kc.课程号
add 课程名='计算机基础'
3.创建存储过程:
//根据名字查询平均成绩,输入参数,输出参数
create proc pxs_avgByName(
@name char(8) ,@avg float output
)
as
set @avg=(select avg(成绩)
from xs,xs_kc
where xs.学号=xs_kc.学号
and xs.姓名=@name)
go
//执行存储过程
declare @ag float
exec pxs_avgByName '李林',@avg output
select '平均分' =@ag
4.创建触发器:
//如果在XS表中添加或修改的学生学号不是以“08”开头,
//则使用RAISERROR语句向客户端显示一条信息“学号必修以08开头”。
create trigger tri_n
on xs
for insert,update
as
declare @i char(6)
select @i=学号 from inserted
if @i not like '08%'
begin
ROLLBACK TRANSACTION
RAISERROR ('学号必修以08开头,操作已经撤消!', 16, 10)
end
go
--一一一一一一一一一一一一一一一一一一一一一
//插入数据
public void insertData(SQLiteDatabase db,String table,Article article){
ContentValues values = new ContentValues();
values.put("title",article.getTitle());
values.put("author", article.getAuthor());
db.insert(table, null, values);
}
//删除数据
public void deletData(SQLiteDatabase db,String table,Integer id){
db.delete(table, "_id=?", new String[]{id.toString()});
}
//根据id修改数据
public void updataData(SQLiteDatabase db,String table,Integer id,Article article){
ContentValues values = new ContentValues();
values.put("title",article.getTitle());
values.put("author", article.getAuthor());
db.update(table, values, "_id=?", new String[]{id.toString()});
}
//根据id查询数据库
public Article selectData(SQLiteDatabase db,String table,Integer id){
Cursor cursor = db.query(table,null, "_id=?", new String[]{id.toString()}, null, null, null);
if(cursor.moveToFirst()){
String title = cursor.getString(cursor.getColumnIndex("title"));
String author = cursor.getString(cursor.getColumnIndex("author"));
return new Article(title,author);
}
return null;
}
//查询数据库所有数据
public List<Article> selectDatas(SQLiteDatabase db,String table){
List<Article> articles = new ArrayList<Article>();
Cursor cursor = db.query(table,null, null, null, null, null, null);
while(cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String title = cursor.getString(cursor.getColumnIndex("title"));
articles.add(new Article(id,title));
}
return articles;
}
]]
--[[==============;;;=数据库操作==;;=============]]
--导入包
import "android.database.sqlite.*"
tbname="tb_note"--表名
dbname="notes.db"
dbpath=this.getLuaDir().."/"..dbname--存放路径
--打开数据库(没有自动创建)
db = SQLiteDatabase.openOrCreateDatabase(dbpath,MODE_PRIVATE, nil);
--execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句
function exec(sql)
db.execSQL(sql);
end
--rawQuery()方法用于执行select语句。
function raw(sql,text)
cursor=db.rawQuery(sql,text)
end
--创建数据库表
function createdbtable()
--查询表是否存在
local sql="select count(*) from sqlite_master where type='table' and name = '"..tbname.."'"
if pcall(raw,sql,nil) then
cursor.moveToNext()
local nn=cursor.getInt(0)
if nn < 1 then
sql="create table "..tbname.."(id integer primary key,t_data text,t_date varchar(20))"
if pcall(exec,sql) then
return 1--创建成功
else
return 0--创建失败
end
else
return -1--表已存在
end
end
end
--添加数据
function adddata(da,de)
if pcall(exec,"insert into "..tbname.." (t_data,t_date) values('"..da.."','"..de.."')") then
return true--添加成功
else
return false--添加失败
end
end
--删除数据
function deldata(d)
if pcall(exec,"delete from "..tbname.." where id="..d) then
return true--成功
else
return false--失败
end
end
--更新数据
function deldata(da,d)
--根据id更新数据,不更新创建时间
if pcall(exec,"update "..tbname.." set t_data='"..da.."' where id="..d) then
return true--成功
else
return false--失败
end
end
--查询数库
function seldata(sql)
local ddts={}
if pcall(raw,sql,nil) then
while (cursor.moveToNext()) do
local tid = cursor.getInt(0);
local tda = cursor.getString(1);
local tde = cursor.getString(2);
table.insert(ddts,{id=tid,date=tda,data=tde});
end
cursor.close()
else
--print("查询失败")
end
return ddts
end
--查询所有
function seldata()
return seldata("select * from "..tbname)
end
--[[==============;;;=数据库操作==;;=============]]
sqlite一些知识
Mlua打包时
在项目文件夹中可自定义欢迎页面[welcome.png]和APP图标[icon.png],打包时可自动替换自定义的文件。