日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

android面向数据库的的编程工具-OrmLite

發布時間:2025/3/20 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android面向数据库的的编程工具-OrmLite 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據庫操作框架OrmLite

  • ORMlite是類似hibernate的對象映射框架,主要面向java語言,同時,是時下最流行的android面向數據庫的的編程工具。
  • 對象關系映射(Object Relational Mapping,簡稱ORM)是通過使用描述對象和數據庫之間映射的元數據,將面向對象語言程序中的對象自動持久化到關系數據庫中。本質上就是將數據從一種形式轉換到另外一種形式

對象與表的關系

具體使用

1.導入OrmLite依賴
implementation ‘com.j256.ormlite:ormlite-android:5.0’

2.設置網絡權限

3.創建Person對象,定義Person類與表的關系

import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; //將person類與表對應,映射 @DatabaseTable(tableName = "person") public class Person {//將成員變量與表的列對應@DatabaseField(columnName = "id",generatedId = true)public Integer id;@DatabaseField(columnName = "name")public String name;@DatabaseField(columnName = "age")public Integer age;public Person() {}public Person(Integer id, String name, Integer age) {this.id = id;this.name = name;this.age = age;}@Overridepublic String toString() {return "Person{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';} }

4.根據映射關系創建數據庫和表

public class MainActivity extends AppCompatActivity {//根據映射關系創建數據庫和表public class MyHelper extends OrmLiteSqliteOpenHelper{public MyHelper(Context context) {super(context, "person", null, 1);//參數1:上下文,參數2:數據庫名}@Overridepublic void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {try {//根據映射關系創建表TableUtils.createTable(connectionSource,Person.class);} catch (SQLException e) {e.printStackTrace();}}@Overridepublic void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {}}

5.增刪改查操作

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//定義一個Person對象Person person1 = new Person(null,"張三",20);Person person2 = new Person(null,"李四",22);//創建myHelper對象,創建數據庫和表MyHelper myHelper = new MyHelper(this);try {//獲得一個具有增刪改查的對象,叫做Dao對象//<類,id類型>Dao<Person, Integer> dao = myHelper.getDao(Person.class);//增 // dao.create(person1); // dao.create(person2);//dao.createIfNotExists() 如果不存在則創建//刪 // dao.deleteById(5);//改,先查再改再更新Person p = dao.queryForId(6);p.name = "趙五";dao.update(p);//查List<Person> person = dao.queryForAll();System.out.println("結果"+person);} catch (SQLException e) {System.out.println("錯誤");}}

結果:

總結

以上是生活随笔為你收集整理的android面向数据库的的编程工具-OrmLite的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。