我是Xamarin的新人。我想学习基本的插入功能。当我开始点击按钮时我收到了未处理的异常。我认为我的Path文件夹是对的。我不知道我犯了什么错。希望你们能帮我解决这个问题。谢谢你提前。
NewTravelPage.xaml.cs
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelRecordApp.Model;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TravelRecordApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NewTravelPage : ContentPage
{
public NewTravelPage ()
{
InitializeComponent ();
}
public void ToolBarItem_Clicked(Object sender, EventArgs e)
{
Post post = new Post()
{
Experience = experienceEntry.Text
};
SQLiteConnection connection = new SQLiteConnection(App.DatabaseLocation);
connection.CreateTable<Post>();
int rows = connection.Insert(post);
connection.Close();
if (rows > 0)
{
DisplayAlert("Success", "Experience successfully inserted", "OK!");
}
else
{
DisplayAlert("Failed", "Experience failed to inserted", "ok!");
}
}
}
}
MainActivity.cs(Android文件夹)
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.IO;
namespace TravelRecordApp.Droid
{
[Activity(Label = "TravelRecordApp", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
string fileName = "travel_db.sqlite";
string folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string fullPath = Path.Combine(folderPath, fileName);
LoadApplication(new App(fullPath));
}
}
}
答案 0 :(得分:1)
SQLiteConnection
需要connectionString
,而不仅仅是数据库的路径。
你正在传递:
/data/data/com.companyname.TravelRecordApp/files/travel_db.sqlite
预期传递:
Data Source=/data/data/com.companyname.TravelRecordApp/files/travel_db.sqlite
试试这一行:
SQLiteConnection connection = new SQLiteConnection("Data Source=/data/data/com.companyname.TravelRecordApp/files/travel_db.sqlite");
答案 1 :(得分:0)
传递数据库路径时,需要正确传递连接字符串(而不仅仅是DB文件的路径)。
例如:
SQLiteConnection connection = new SQLiteConnection("Data Source=C:\\PATH_TO_DB\db.sqlite;");