using System;
using System.IO;
using System.Data.SqlServerCe;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Common;
using System.Runtime.InteropServices;
using System.Threading;
namespace SerialPort_SqlCe
{
///
/// DataAccess 的摘要说明。
///
public class Class1
{
#region 对数据库的操作
private SqlCeConnection conn = null;
///
/// 打开数据库连接
///
public void OpensqlCeConnection()
{
if(conn == null)
{
conn = new SqlCeConnection();
}
if(conn.State == ConnectionState.Closed)
{
try
{
conn.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
///
/// 关闭数据库连接
///
public void ClosesqlCeConnection()
{
if(conn != null)
{
if(conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
///
/// 创建数据库
///
///
public SqlCeEngine CreateSqlCeDatabase()
{
if (File.Exists ("ResidentFlash\\Test.sdf") ) //确定指定的文件是否存在
File.Delete ("ResidentFlash\\Test.sdf"); //删除指定的文件。如果指定的文件不存在,则不引发异常。
SqlCeEngine engine = new SqlCeEngine ("Data Source = ResidentFlash\\Test.sdf");
engine.CreateDatabase ();
conn = new SqlCeConnection ("Data Source = ResidentFlash\\Test.sdf");
OpensqlCeConnection();
ClosesqlCeConnection();
return engine;
}
///
/// 创建表格
///
public SqlCeCommand CreateTable()
{
conn = new SqlCeConnection ("Data Source = ResidentFlash\\Test.sdf");
OpensqlCeConnection(); //打开连接
SqlCeCommand sqlCeCommand = conn.CreateCommand ();
sqlCeCommand.CommandText =
"CREATE TABLE TestTbl (col1 INT PRIMARY KEY)";
sqlCeCommand.ExecuteNonQuery();
ClosesqlCeConnection();
return sqlCeCommand;
}
///
/// 向表中插入数据
///
///
public SqlCeCommand InsertData(int p1)
{
conn = new SqlCeConnection ("Data Source = ResidentFlash\\Test.sdf");
OpensqlCeConnection(); //打开连接
SqlCeCommand cmd = conn.CreateCommand ();
cmd.CommandText = "INSERT INTO TestTbl (col1) VALUES (?)";
cmd.Parameters.Add(new SqlCeParameter("p1", SqlDbType.Int));
cmd.Prepare();
cmd.Parameters["p1"].Value = p1;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
MessageBox.Show("Insert Data OK!");
ClosesqlCeConnection();
return cmd;
}
///
///执行读的命令
///
///
public string ReadData()
{
conn = new SqlCeConnection ("Data Source = ResidentFlash\\Test.sdf");
OpensqlCeConnection(); //打开连接
MessageBox.Show("open read ");
SqlCeCommand sqlCeCommand = conn.CreateCommand();
sqlCeCommand.CommandText =
"SELECT * FROM TestTbl";
sqlCeCommand.ExecuteNonQuery();
MessageBox.Show("select * from testtb1");
SqlCeDataReader rdr = sqlCeCommand.ExecuteReader();
string aa = null;
if(rdr.Read())
{
aa = (" col1 = " + rdr.GetInt32(0)
// " col2 = " + rdr.GetString(1) );
);
MessageBox.Show("Read data OK!");
return aa;
}
else
{
MessageBox.Show("Read data failed");
return aa;
}
}
#endregion