我們知道通常我們開發的時候都要考慮把用戶的數據存儲到一個數據庫裏面,而這個數據庫則考慮到了整個應用的性能上面,這裏我們不考慮SQL server的數據庫,我們考慮較爲輕量的數據庫進行存儲。
首先我們新建一個項目,然後把界面用代碼處理一下
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="把數據存儲入數據庫"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontFamily="楷體"
FontSize="24"
Foreground="Green"/>
<TextBlock Text="MySQLite Connection Test"
HorizontalAlignment="Center"
FontSize="36"
FontFamily="Gabriola"
Grid.Row="1"
Foreground="Green"/>
<TextBlock Text="用戶賬號:"
Grid.Row="2"/>
<TextBox x:Name="MyTextBox"
Grid.Row="3"
PlaceholderText="name"/>
<TextBlock Text="用戶密碼:"
Grid.Row="4"/>
<PasswordBox x:Name="MyPassWordBox"
Grid.Row="4"
PlaceholderText="password"
Margin="0,20,0,0"/>
<Page.BottomAppBar>
<CommandBar IsOpen="False"
ClosedDisplayMode="Minimal"
Background="Green">
<AppBarButton x:Name="Add"
Label="Add"
Icon="Add"
Click="Add_Click"/>
<AppBarButton x:Name="Show"
Label="Show"
Icon="Zoom"
Click="Show_Click"/>
</CommandBar>
</Page.BottomAppBar>
然後我們再來處理一下界面後臺的事件代碼處理
string path;
SQLite.Net.SQLiteConnection conn;
到這裏的時候我們忘記了一件事,沒有安裝相關的插件,所以再安裝下數據庫插件
還要再安裝一個插件
緊接着我們安裝好了插件後,我再來添加引用,讓項目得到插件的支持
好了,這次可以好好的寫代碼了,我在項目中新增了一個類
public class MyTest
{
[PrimaryKey,AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string PassWord { get; set; }
}
我回到我們的主界面的後臺寫寫代碼
path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalCacheFolder.Path, "db.MySQLite");
conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);
conn.CreateTable<MyTest>();
新增事件的後臺的代碼處理
private void Add_Click(object sender, RoutedEventArgs e)
{
var add = conn.Insert(new MyTest()
{
Name = MyTextBox.Text,
PassWord = MyPassWordBox.Password
});
Debug.WriteLine(path);
}
這裏的這個方法是在visual studio 2015中顯示實時新增的數據
private void Show_Click(object sender, RoutedEventArgs e)
{
var query = conn.Table<MyTest>();
string result = String.Empty;
foreach (var item in query)
{
result = String.Format("{0}:{1}:{2}", item.Id, item.Name,item.PassWord);
Debug.WriteLine(result);
}
}
代碼寫到這裏就已經寫完了,我們看看目的達到了沒有
我們再來看看第二次的效果如何
很顯然我們寫的數據成功的存儲到了SQLite的數據庫中,所以我們的目的就達到了!!!!