我正在编写一种方法,将 Student 插入到本地 SQL 数据库中,该数据库包含一个包含 Students 信息的表:
public void AddStudent(string name, string teachName, string pass)
{
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\Logo.sdf";
SqlCeConnection connection = new SqlCeConnection("Data Source=" + dbfile + "; Password = 'dbpass2011!'");
connection.Open();
SqlCeTransaction transaction = connection.BeginTransaction();
SqlCeCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "INSERT INTO Students VALUES ('@name', '@id', '@pass', '@tname')";
command.Parameters.Add("@name", name);
command.Parameters.Add("@id", this.ID);
command.Parameters.Add("@pass", MD5Encrypt.MD5(pass));
command.Parameters.Add("@tname", teachName);
command.Prepare();
command.ExecuteNonQuery();
transaction.Commit();
connection.Dispose();
connection.Close();
}
每当我使用它时,当我查看数据库中 Students 表的内容时,它永远不会将数据插入表中。最初我让这个返回一个 int,这样我就可以看到它影响了多少行,它总是返回 1,所以我知道它在工作。
我一直在寻找这个问题的答案,而类似问题的答案是提问者查看的是错误的 .sdf 文件。我确定我正在查看正确的文件。
如有任何反馈,我们将不胜感激!
最佳答案
command.CommandText = "INSERT INTO Students VALUES ('@name', '@id', '@pass', '@tname')";
您应该删除多余的单引号 - 这应该是:
command.CommandText = "INSERT INTO Students VALUES (@name, @id, @pass, @tname)";
此外,我不确定您为什么要为单个插入打开一个事务 - 这也不需要。
关于c# - 无法使用 C# 将数据插入 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8206956/