对您的代码的一些评论:
- 代码中的错字(后期更新)
- C# 布尔值≠Transact-SQL 位。
- 您进行了 SQL 注入。
- 您可以将
IDENTITY 用于StudentID 列
代码中的错字
我还在你的代码中看到你的插入语句末尾有一个错字,你使用这个:
/*...*/ "',"' +chk.Transferee+ '")";
而不是这个:
/*...*/ "'," + chk.Transferee.IsChecked + ")";
异或这个:
/*...*/ "','" + chk.Transferee.IsChecked + "')";
无论如何它是 SQL 注入,chk.Transferee.IsChecked 是 C# 布尔值而不是 Transact-SQL 位。所以我们可以转到下一个标题。
C# boolean ≠ Transact-SQL 位
如果你运行下面的代码:
using System;
public class Program
{
public static void Main()
{
bool? yes = true;
Console.WriteLine("yes: {0}", yes);
bool? no = false;
Console.WriteLine("no: {0}", no);
bool? nothing = null;
Console.WriteLine("nothing: {0}", nothing);
}
}
它会打印这个:
yes: True
no: False
nothing:
你可以在这个.NET fiddle上测试它。
Transact-SQL 对“true”或“false”使用一点。在 Transact-SQL 中,这分别是 1 和 0。如果错字已修复,您愿意使用此代码执行的操作分别是:
insert into StudentTable([StudentID], [Lastname], [Transferee])
values (7, 'Turner', True)
异或这个:
insert into StudentTable([StudentID], [Lastname], [Transferee])
values (7, 'Turner', 'True')
这不是 Transact-SQL 的有效代码。因为布尔值true 和值为True 的字符串不是1 位。
除此之外:可为空的布尔值(仅当您使用 WPF 或必须插入 null 时)
如果您使用的是 WPF,则为 IsChecked property is nullabele,或者如果您将插入 null。您的代码将给出一个例外。这将是您的 SQL 查询:
insert into StudentTable([StudentID], [Lastname], [Transferee])
values (7, 'Turner', )
异或这个:
insert into StudentTable([StudentID], [Lastname], [Transferee])
values (7, 'Turner', '')
这当然是无效的。
正确陈述
正确的说法应该是这样的:
insert into StudentTable([StudentID], [Lastname], [Transferee])
values (7, 'Turner', 1)
在SQLfiddle 中测试这段代码。
防止 SQL 注入
维基百科说SQL injection:
SQL 注入是一种代码注入技术,用于攻击数据驱动的应用程序,其中恶意的 SQL 语句被插入到输入字段中以执行(例如,将数据库内容转储给攻击者)。
您可以使用以下代码代替您的代码:
command.CommandText = @"insert into StudentTable([StudentID], [Lastname], [Transferee])
values (@StudentID, @LastName,@Transferee)";
command.Parameters.AddWithValue("@StudentID", txtStudentID.Text);
command.Parameters.AddWithValue("@LastName", txtLastname.Text);
command.Parameters.AddWithValue("@Transferee", chk.Transferee.IsChecked);
// @ClintJoe: Will you check code of line above I think it's not correct.
// must it not to be this: `chk.IsChecked`? Not sure.
如果你使用上面的代码并解决了我添加的注释,第一个(你的代码中的错字),第二个标题(C# boolean ≠ Transact-SQL bit)的所有问题) 问题就解决了。
这也将防止 SQL 注入。但是,为什么没有 SQL 注入?看这幅漫画:
身份
提示:同时创建列StudentIDidentity。
IDENTITY 在表中创建标识列。此属性与CREATE TABLE 和ALTER TABLE Transact-SQL 语句一起使用。
完成此操作后,您可以使用以下代码:
command.CommandText = @"insert into StudentTable([Lastname], [Transferee])
values (@LastName, @Transferee)";
command.Parameters.AddWithValue("@LastName", txtLastname.Text);
command.Parameters.AddWithValue("@Transferee", chk.Transferee.IsChecked);
并且不再需要在应用程序中请求或创建唯一 ID
注意
MS-access 不是一个好用的数据库。通过在 Google 上的快速搜索,我发现了 Access 的主要缺点:
- 取决于 Windows 和 Office 版本。
- Access 没有触发器和高级功能。
- Access VBA 是一种解释型语言。因此它很慢。
- 不存在用于性能分析和优化数据库的访问工具。
- 如果您有超过 5-10 个并发用户,即使在拆分(前端/后端)数据库中,访问也会变得非常缓慢。
- 当访问文件变得太大(>100MB/mdb)时,访问文件很容易损坏。
- 即使在拆分数据库上,Access 也总是在客户端计算所有内容。
来源:What are the major disadvantages of Microsoft Access? - Quora