Visual Studio C# 和 SQL Compact(连接、选择、插入)的基本入门? [英] Basic start with Visual Studio C# and SQL Compact (connect, select, insert)?

查看:23
本文介绍了Visual Studio C# 和 SQL Compact(连接、选择、插入)的基本入门?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 SQL CE 学习 C#,以便我的程序可以记住内容.

I'm trying to learn about C# with SQL CE so that my program can remember stuff.

我已经创建了一个数据库并且可以连接到它:

I have created a database and can connect to it:

SqlCeConnection conn = 
         new SqlCeConnection(@"Data Source=|DataDirectory|\dbJournal.sdf");
conn.Open();

而且它连接正确,我猜是因为如果我将 dbJournal.sdf 重命名为错误的名称,它不会正确调试.

And it connects right, I guess cause if I rename the dbJournal.sdf to something wrong it doesn't debug right.

假设我想做一个简单的 SELECT 查询.

Let's say I want to make a simple SELECT query.

(SELECT * FROM tblJournal)

这是怎么做到的?

简单的插入怎么样?

(INSERT TO tblJournal (column1, column2, column2) VALUES 
                                        (value1, value2, value3))

我已经习惯了 PHP 和 MySQL(正如你所见:o))

I'm used to PHP and MySQL (as you properly can see :o))

推荐答案

@Chuck 提到 EntityFramework 可以简化事情并为您完成编写 sql 的所有工作.

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

但是这里有一个基本的 ADO.NET 方法,我将在下面描述.

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

这些类遵循标准模式,以便从 sql server 或其他数据库插入/读取,有精确的副本类,如 SqlConnectionOleDbConnectionOleDbCommand

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

这是最准系统的 ado.net 方法:

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();
}

然后读取数据:

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);
}

这会将整个数据一次性放入DataTable 类.

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

插入数据:

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

这篇关于Visual Studio C# 和 SQL Compact(连接、选择、插入)的基本入门?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆