下面是使用参数插入数据,我认为这是一种更好的方法:
var insertSQL = "INSERT INTO yourTable (firstName, lastName, email, phone) VALUES (firstName, lastName, email, phone)";
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
{
cn.Open();
cmd.Parameters.Add("firstName", SqlDbType.NVarChar);
cmd.Parameters.Add("lastName", SqlDbType.NVarChar);
cmd.Parameters.Add("email", SqlDbType.NVarChar);
cmd.Parameters.Add("phone", SqlDbType.NVarChar);
cmd.Parameters["firstName"].Value = firstName;
cmd.Parameters["lastName"].Value = lastName;
cmd.Parameters["email"].Value = email;
cmd.Parameters["phone"].Value = phone;
cmd.ExecuteNonQuery();
}
这是从数据库中选择数据并填充 datagridview:
var dt = new DataTable();
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString )
using (var cmd = new SqlCeCommand("Select * From yourTable", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
//resize the DataGridView columns to fit the newly loaded content.
yourDataGridView.AutoSize = true; yourDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
//bind the data to the grid
yourDataGridView.DataSource = dt;
}
}