服务器之家

服务器之家 > 正文

Android SQLite数据库操作代码类分享

时间:2021-03-15 15:07     来源/作者:Android开发网

使用示例:

?
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
package cn.hackcoder.beautyreader.db;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 
/**
 * Created by hackcoder on 15-1-25.
 */
public class DataBaseHelper extends SQLiteOpenHelper {
  private static final String dbName = "sample.db";
  private static int dbVersion = 1;
 
  public DataBaseHelper(Context context) {
    super(context,dbName,null,dbVersion);
  }
 
  @Override
  public void onCreate(SQLiteDatabase db) {
    Log.d("===========","数据库初始化");
    //建表
    String sql = "create table if not exists tb_article(id integer primary key autoincrement,title varchar(50),content TEXT,url varchar(50),page integer)";
    db.execSQL(sql);
  }
 
  /**
   *
   * @param db
   * @param oldVersion
   * @param newVersion
   */
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
  }
}

类源码:

?
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package cn.hackcoder.beautyreader.service;
 
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
 
import java.util.ArrayList;
import java.util.List;
 
import cn.hackcoder.beautyreader.db.DataBaseHelper;
import cn.hackcoder.beautyreader.model.Article;
 
/**
 * Created by hackcoder on 15-1-25.
 */
public class ArticleService {
 
  private DataBaseHelper dataBaseHelper;
  private SQLiteDatabase readableDatabase;
  private SQLiteDatabase writableDatabase;
 
  public ArticleService(Context context) {
    dataBaseHelper = new DataBaseHelper(context);
  }
 
  public void add(Article article) {
    String sql = "insert into tb_article(id,title,content,url,page) values(?,?,?,?,?)";
    getReadableDatabase().execSQL(sql, new Object[]{null, article.getTitle(), article.getContent(), article.getUrl(), article.getPage()});
  }
 
  public void delete(int id) {
    String sql = "delete from tb_article where id =?";
    getReadableDatabase().execSQL(sql, new Object[]{id});
  }
 
  public void deleteAll() {
    String sql = "delete from tb_article";
    getReadableDatabase().execSQL(sql,null);
  }
  public void update(Article article) {
    String sql = "update tb_article set id="codetool">
标签:

相关文章

热门资讯

返回顶部