Basic start with Visual Studio C# and SQL Compact (connect, select, insert)?

帅比萌擦擦* 提交于 2019-12-04 04:50:32
gideon

@Chuck mentions EntityFramework which simplifies things and does all the work of writing the sql for you.

But there is a basic ADO.NET approach here which I will describe below.

The classes follow a standard pattern so to insert/read from sql server or other databases there are exact replica classes like SqlConnection or OleDbConnection and OleDbCommand etc

This is the most barebones ado.net approach:

using( SqlCeConnection conn =
          new SqlCeConnection(@"Data Source=|DataDirectory|\dbJournal.sdf") )
using( SqlCeCommand cmd = conn.CreateCommand() )
{
  conn.Open();
  //commands represent a query or a stored procedure       
  cmd.CommandText = "SELECT * FROM tblJournal";
  using( SqlCeDataReader rd = cmd.ExecuteReader() )
  {
     //...read
  }
  conn.Close();
}

Then to read data :

while (rd.Read())
{//loop through the records one by one
     //0 gets the first columns data for this record
     //as an INT
     rd.GetInt32(0);
     //gets the second column as a string
     rd.GetString(1);
}

A nice and quicker way to read data is like this:

using( SqlCeDataAdapter adap = 
          new SqlCeDataAdapter("SELECT * FROM tblJournal", "your connection") )
{
  //the adapter will open and close the connection for you.
  DataTable dat = new DataTable();
  adap.Fill(dat);
}

This gets the entire data in one shot into a DataTable class.

To insert data :

SqlCeCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = "INSERT TO tblJournal (column1, column2, column2) 
                           VALUES (value1, value2, value3)";
cmdInsert.ExecuteNonQuery();

If you just start learning that i will suggest you to use LINQ to make that queries.

Here is MSDN article showing features of LINQ.

http://msdn.microsoft.com/en-us/library/bb425822.aspx

Using LINQ it will be simple to do every query. For example, you can write your select query like this

from journal in TblJournal select journal 

or just

context.TblJournal

also in order to improve performence , you better keep the conncection open all the time when working with SQL CE (as opposed to other standard sql databases)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!