我正在尝试使用 SQL CE 学习 C#,以便我的程序能够记住一些东西。
我已经创建了一个数据库并且可以连接到它:
SqlCeConnection conn =
new SqlCeConnection(@"Data Source=|DataDirectory|\dbJournal.sdf");
conn.Open();
它连接正确,我猜是因为如果我将 dbJournal.sdf
重命名为错误的东西,它就无法正确调试。
假设我想做一个简单的 SELECT 查询。
(SELECT * FROM tblJournal)
这是怎么做到的?
简单的插入怎么样?
(INSERT TO tblJournal (column1, column2, column2) VALUES
(value1, value2, value3))
我已经习惯了 PHP 和 MySQL(如您所见:o))
最佳答案
@Chuck 提到了 EntityFramework,它简化了事情并为您完成了编写 sql 的所有工作。
但是这里有一个基本的 ADO.NET 方法,我将在下面描述。
这些类遵循标准模式,因此要从 sql server 或其他数据库中插入/读取有精确的副本类,如 SqlConnection
或 OleDbConnection
和 OleDbCommand
等
这是最准系统的 ado.net 方法:
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);
}
读取数据的一种不错且更快的方法是这样的:
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 中类。
插入数据:
SqlCeCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = "INSERT TO tblJournal (column1, column2, column2)
VALUES (value1, value2, value3)";
cmdInsert.ExecuteNonQuery();
关于c# - 从 Visual Studio C# 和 SQL Compact(连接、选择、插入)开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9818169/