使用SqlCeDataAdapter将新行插入c#中的本地数据库
本文关键字:数据库 SqlCeDataAdapter 新行 插入 使用 | 更新日期: 2023-09-27 18:25:00
我有一个本地SQL Server CE数据库(mainDB.sdf
),其中只有一个名为Users
的表。
它由7列组成:
Name (ntext)
Surname (ntext)
Nickname (nchar, unique, primary key)
Gender (ntext)
Status (ntext)
City (ntext)
Photo (image)
我使用对象:
private SqlCeConnection connection;
private SqlCeDataAdapter adapter;
private SqlCeCommandBuilder builder;
private DataSet data;
首先,我连接到一个数据库:
connection = new SqlCeConnection("Data Source = mainDB.sdf");
connection.Open();
SqlCeCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Users";
adapter = new SqlCeDataAdapter(cmd);
builder = new SqlCeCommandBuilder();
builder.DataAdapter = adapter;
data = new DataSet();
adapter.Fill(data);
我尝试插入新行:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] im = ms.ToArray();
DataRow newRow = data.Tables[0].NewRow();
newRow["Name"] = textBox1.Text;
newRow["Surname"] = textBox2.Text;
newRow["Nickname"] = textBox3.Text;
newRow["Gender"] = listBox1.Text.Length > 0 ? listBox1.Text : null;
newRow["Status"] = radioButton1.Checked ? "Student" : radioButton2.Checked ? "Professional" : null;
newRow["City"] = comboBox1.Text.Length > 0 ? comboBox1.Text : null;
newRow["Photo"] = im;
data.Tables[0].Rows.Add(newRow);
adapter.Update(data);
connection.Close();
在这之后,我转到表Users,没有新的数据。我认为SqlCeCommandBuilder应该生成所需的命令。我在这里错过了什么?
重要编辑:
一切都很好。c似乎创建了两个到数据库的链接。第一个在名为mainDB.sdf
的项目文件夹中,它是空的。但在bin'Debug
文件夹中还有另一个。作为一个绝对的新手,我不知道这一点。我可以得到数据库mainDB.sdf1
中所有先前的行,选择New Query
并输入SELECT * FROM USERS
。与第一个mainDB.sdf
相同的命令没有给出任何结果。这就是问题所在。
使用SqlCeCommand
SqlCeConnection connection = new SqlCeConnection("Data Source = mainDB.sdf");
connection.Open();
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO Users (Name, Surname, Nickname, Gender, Status, City, Photo) Values(@name,@surname,@nickname,@gender,@status,@city,@photo)", connection))
{
com.Parameters.AddWithValue("@name", textBox1.Text);
com.Parameters.AddWithValue("@surname", textBox2.Text);
com.Parameters.AddWithValue("@nickname", textBox3.Text);
com.Parameters.AddWithValue("@gender", listBox1.Text.Length > 0 ? listBox1.Text : null);
com.Parameters.AddWithValue("@status", radioButton1.Checked ? "Student" : radioButton2.Checked ? "Professional" : null);
com.Parameters.AddWithValue("@city", comboBox1.Text.Length > 0 ? comboBox1.Text : null);
com.Parameters.AddWithValue("@photo", im);
com.ExecuteNonQuery();
}
connection.Close();