如何将SQLite3 创建的数据库与android 程序连接

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将SQLite3 创建的数据库与android 程序连接相关的知识,希望对你有一定的参考价值。

Sqlite3是android自带的一种轻型的数据库,使用的话也是很方便的。
下面是例子:
package yeshu.sqlite3;

import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

public class sqlite3 extends Activity

private Button createdatabase;

private Button updatedatabase;

private Button insert;

private Button update;

private Button select;

private Button delete;

private EditText edittext01;

private EditText edittext02;

private String name;

private int id;

private String dbname;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

createdatabase = (Button) findViewById(R.id.xxx);

updatedatabase = (Button)findViewById(R.id.Button02);

insert = (Button)findViewById(R.id.Button03);

update = (Button)findViewById(R.id.Button04);

select = (Button)findViewById(R.id.Button05);

delete = (Button)findViewById(R.id.Button06);

edittext01 = (EditText)findViewById(R.id.EditText01);

edittext02 = (EditText)findViewById(R.id.EditText02);

createdatabase.setOnClickListener(new OnClickListener_create());

updatedatabase.setOnClickListener(new OnClickListener_updatedatabase());

insert.setOnClickListener(new OnClickListener_insert());

update.setOnClickListener(new OnClickListener_update());

select.setOnClickListener(new OnClickListener_select());

delete.setOnClickListener(new OnClickListener_delete());



class OnClickListener_delete implements OnClickListener



public void onClick(View v)

// TODO Auto-generated method stub

id = Integer.parseInt(edittext01.getText().toString());

Data temp = new Data(sqlite3.this, "data_yeshu");

SQLiteDatabase db = temp.getWritableDatabase();

db.delete("user", "id=?", new String[]id+"");





class OnClickListener_insert implements OnClickListener



public void onClick(View v)

// TODO Auto-generated method stub

name = edittext02.getText().toString();

id = Integer.parseInt(edittext01.getText().toString());

Data temp = new Data(sqlite3.this, "data_yeshu");

SQLiteDatabase db = temp.getWritableDatabase();

ContentValues value = new ContentValues();

value.put("id", id);

value.put("name", name);

db.insert("user", null, value);

System.out.println("insert");





class OnClickListener_update implements OnClickListener



public void onClick(View v)

// TODO Auto-generated method stub

name = edittext02.getText().toString();

id = Integer.parseInt(edittext01.getText().toString());

Data temp = new Data(sqlite3.this, "data_yeshu");

SQLiteDatabase db = temp.getWritableDatabase();

ContentValues value = new ContentValues();

value.put("name", name);

db.update("user", value, "id=?", new String[]id+"");





class OnClickListener_updatedatabase implements OnClickListener



public void onClick(View v)

// TODO Auto-generated method stub

Data temp = new Data(sqlite3.this, "data_yeshu", 2);

SQLiteDatabase db = temp.getReadableDatabase();





class OnClickListener_select implements OnClickListener



public void onClick(View v)

// TODO Auto-generated method stub

Data temp = new Data(sqlite3.this, "data_yeshu");

SQLiteDatabase db = temp.getReadableDatabase();

Cursor cursor = db.query("user", new String[]"id", "name", "id=?", new String[]"1", null, null, null);

while(cursor.moveToNext())



System.out.println(cursor.getShort(cursor.getColumnIndex("id")));

System.out.println(cursor.getString(cursor.getColumnIndex("name")));







class OnClickListener_create implements OnClickListener



public void onClick(View v)

// TODO Auto-generated method stub

Data temp = new Data(sqlite3.this, "data_yeshu");

SQLiteDatabase db = temp.getReadableDatabase();







================================

package yeshu.sqlite3;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.database.sqlite.SQLiteOpenHelper;

public class Data extends SQLiteOpenHelper

private static final int VERSION = 1;

public Data(Context context, String name, CursorFactory factory,

int version)

super(context, name, factory, version);

// TODO Auto-generated constructor stub



public Data(Context context, String name, int version)



this(context, name, null, version);



public Data(Context context , String name)



this(context, name, null, VERSION);



@Override

public void onCreate(SQLiteDatabase db)

// TODO Auto-generated method stub

System.out.println("create a new database");

db.execSQL("create table user(id int, name VERCHAR(20))");



@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

// TODO Auto-generated method stub

System.out.println("update a database");



参考技术A 连接代码?网上搜搜。。

如何与SQLite建立关系(外键)

我正在尝试在SQLite中创建与我的表的关系(我目前正在使用Xamarin.Forms),但是我没有得到预期的结果,添加数据注释[ForeignKey(typeof(UserLocal))]但是我没有在我的BD中创建关系, 这是怎么回事?我的BD只执行索引关系,但它没有将它们与外键相关联

Browser SQLite

为了连接到我的数据库,我创建了一个接口,在Android和iOS中获取路由,然后管理我的INSERT,UPDATE,DELETE等...我是从DataService.CS服务中做到的。

ANDROID:

[assembly: Xamarin.Forms.Dependency(typeof(PathService))]
namespace AppValora.Droid.Implementation

    public class PathService : IPathService
    
        public string GetDatabasePath()
                      
            string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
            var directoryPath = Path.Combine(path, "Valora/Databases");
            if (!Directory.Exists(directoryPath))
            
                try
                

                    Directory.CreateDirectory(directoryPath);
                
                catch (Exception ex)
                

                
            
            return Path.Combine(directoryPath, "Valora.db3");
        
    

iOS版:

[assembly: Dependency(typeof(PathService))]
namespace AppValora.iOS.Implementation

    public class PathService : IPathService
    
        public string GetDatabasePath()
        
            string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string libFolder = Path.Combine(docFolder, "..", "Library");

            if (!Directory.Exists(libFolder))
            
                Directory.CreateDirectory(libFolder);
            

            return Path.Combine(libFolder, "Valora.db3");
        
    

DATASERVICE.CS:

#region Servicios
private SQLiteAsyncConnection connection;
private DialogService dialogService;       
#endregion

#region Constructor
public DataService()

    dialogService = new DialogService();
    OpenOrCreateDB();

#endregion

private async Task OpenOrCreateDB()

    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);

    if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
    
        if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync((Plugin.Permissions.Abstractions.Permission.Storage)))
        
            await dialogService.ShowMessage("!ATENCIÓN!", "Valora necesita el permiso de archivos para este proceso.");
        

        var results = await CrossPermissions.Current.RequestPermissionsAsync((Plugin.Permissions.Abstractions.Permission.Storage));
        //Best practice to always check that the key exists
        if (results.ContainsKey(Plugin.Permissions.Abstractions.Permission.Storage))
            status = results[Plugin.Permissions.Abstractions.Permission.Storage];
    

    if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
    
        //CONSULTO PATH
        var databasePath = DependencyService.Get<IPathService>().GetDatabasePath();
        //CREO LA CONEXION
        this.connection = new SQLiteAsyncConnection(databasePath);
        //CREACION DE TABLAS
        await connection.CreateTableAsync<UserLocal>().ConfigureAwait(false);
        await connection.CreateTableAsync<Companie>().ConfigureAwait(false);
    
    else if (status != Plugin.Permissions.Abstractions.PermissionStatus.Unknown)
    

        

    public async Task Insert<T>(T model)
    
        await this.connection.InsertAsync(model);
    

除了建立连接之外,DataService还创建了我想要生成关系的表,数据模型如下...

USERLOCAL.CS:

public class UserLocal

    [PrimaryKey, AutoIncrement]
    public int Id  get; set; 

    public int IdLogin  get; set; 
    public string Token  get; set;              
    public string Nombre  get; set; 
    public string Rut  get; set; 
    public bool Recordado  get; set; 
    public string Password  get; set; 

    [OneToMany]
    public List<Companie> Companies  get; set; 

COMPANIE.CS:

public class Companie

    [PrimaryKey, AutoIncrement]
    public int Id  get; set; 

    public int IdLogin  get; set; 
    public string Nombre  get; set; 
    public bool Principal  get; set; 
    public bool ExternalCorp  get; set; 
    public bool IsCorporate  get; set; 

    [ForeignKey(typeof(UserLocal))]
    public int IdUser  get; set; 

    [ManyToOne]
    public UserLocal UserLocal  get; set; 

接下来,下面显示了如何在我的表中插入记录的代码,我认为在这部分我错了,因为我无法创建关系

VIEWMODEL.CS:

ListaCompanie.Clear();          

// I WALK THE NUMBER OF COMPANIES THAT I WANT TO ADD
foreach (var item in loginResponse.Companies)

    var companie = new Companie
    
        IdLogin = item.Id,
        Nombre = item.Name,
        ExternalCorp = item.ExternalCorp,
        IsCorporate = item.IsCorporate,
        Principal = item.Principal,
        //CLAVE FORANEA
        IdUser = loginResponse.Id,
    ;

    ListaCompanie.Add(companie);

    await dataService.Insert(companie);


var user = new UserLocal

        IdLogin = loginResponse.Id,
        Nombre = loginResponse.Name,
        Recordado = Settings.Recordado,
        Rut = loginResponse.Rut,
        Token = loginResponse.Token,
        Password = GetSHA1(Settings.Password),
        Companies = ListaCompanie,
;

await dataService.Insert(user);

为什么不生成这些关系?如何将表格与SQLite相关联?我究竟做错了什么?我正在使用具有MVVM架构模式的Xamarin.Forms,对我有什么帮助?

答案

如果你使用SQLite.Net.Extensions创建关系,那么你需要像这样设置CascadeOperations

public class UserLocal

    [PrimaryKey, AutoIncrement]
    public int Id  get; set; 
    public int IdLogin  get; set; 
    public string Token  get; set;              
    public string Nombre  get; set; 
    public string Rut  get; set; 
    public bool Recordado  get; set; 
    public string Password  get; set; 

    // THIS BIT HERE 
    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<Companie> Companies  get; set; 

另一件事是如果你使用这个库,那么你可以insertWithChildren创建这样的关系:

var user = new UserLocal

    IdLogin = loginResponse.Id,
    Nombre = loginResponse.Name,
    Recordado = Settings.Recordado,
    Rut = loginResponse.Rut,
    Token = loginResponse.Token,
    Password = GetSHA1(Settings.Password),
    Companies = ListaCompanie,
;

// I WALK THE NUMBER OF COMPANIES THAT I WANT TO ADD
foreach (var item in loginResponse.Companies)

    var companie = new Companie
    
        IdLogin = item.Id,
        Nombre = item.Name,
        ExternalCorp = item.ExternalCorp,
        IsCorporate = item.IsCorporate,
        Principal = item.Principal,
        //CLAVE FORANEA
        UserLocal = user,
        // You dont need to set this as it will be assigned in InsertWithChildren
        // IdUser = loginResponse.Id,
    ;

    ListaCompanie.Add(companie);

    await dataService.InsertWithChildren(companie);

以上是关于如何将SQLite3 创建的数据库与android 程序连接的主要内容,如果未能解决你的问题,请参考以下文章

如何打开android的sqlite3

Android中如何使用命令行查看内嵌数据库SQLite3

10分钟理解Android数据库的创建与使用(附详解和示例代码)

如何在android自带的sqlite3中创建一个数据库文件,请大虾门详细指导

如何使用 sqlite3.exe 从导出的 .sql 脚本创建数据库

10分钟理解Android数据库的创建与使用(附具体解释和演示样例代码)