北漂IT民工 的博客

Sqlite下得到列名的方法

1.通过下面的语句得到表的创建语句

1
select sql from sqlite_master where type = 'table' and tbl_name = 'table_name';

其中table_name是你要替换掉的表名

2.通过分析sql语句得到各列的名称.

下面是python下的一段分析代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

def isTableExist(self, table_name):

sql = """select name from sqlite_master where type = 'table' and

name = '%s'""" % (table_name)

h = self._cursor.execute(sql)

ret = h.fetchall()

return len(ret) == 1</p>

def isFieldsExist(self, table_name, fields):

sql = """select sql from sqlite_master where type =

'table' and tbl_name = '%s'""" % (table_name)

h = self._cursor.execute(sql)

row = h.fetchone()

old_fields = re.findall("((.*))", row[0])[0].split(",")

tmp_fields = []

for row in old_fields:

tmp_fields.append(row.strip().replace("`", "").split(" ")[0])

for field in fields:

if field not in tmp_fields:

return False

return True

def isFieldsTypesMatch(self, table_name, fields, types):

sql = """select sql from sqlite_master where type =

'table' and tbl_name = '%s'""" % (table_name)

h = self._cursor.execute(sql)

row = h.fetchone()

old_fields = re.findall("((.*))", row[0])[0].split(",")

tmp_fields = {}

for row in old_fields:

tmp = row.strip().replace("`", "").split(" ")

tmp_fields[tmp[0].upper()] = tmp[1].upper()

i = 0

for field in fields:

if tmp_fields[field.upper()] != types[i].upper():

return False

i += 1

return True