所以我只是在学习 .NET、WinForms、SQL Server 和 C#...我以前使用过 VB 和 MS Access,所以我知道这有很大不同,但我正在寻找一个起点。
我通常在 MS Access 中使用非绑定(bind)表单进行数据输入,然后将数据保存到 btn_Click 上的表或使用 Visual Basic(DAO 或 SQL)的按钮事件处理程序。
所以我尝试了 Visual Studio,使用 VB.NET 和 C# 以及 SQL Server 创建 WinForms。我已经学会了如何创建一个WinForm,然后通过VS在其中创建一个DB,并将表单数据绑定(bind)到数据库表。
我无法重现未绑定(bind)的表单,并通过代码(btn 单击)保存到外部数据库。假设我已经通过 SSMS 创建了一个数据库,现在正在创建一个用于数据输入的 WinForm。现在,单击 btn,我正在寻找将输入的数据从表单传输到数据库表的 C# 代码。
为了举例,假设该表单只有一个名为 txtData 的文本框,我想将其传输到名为 DBExample 的数据库、名为 tblExample 的表和名为 fldExample 的字段。
任何人都可以帮我解决这个问题吗?我在网上查找了很多有关执行此操作的信息,但我遇到的所有内容都与控件的数据绑定(bind)有关,并且我正在寻找通过代码来执行此操作。
谢谢 贾斯汀
最佳答案
有关 .NET 数据访问的良好通用引用,请参阅
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
或
http://www.startvbdotnet.com/ado/default.aspx
对您的示例问题的更具体答案:
过滤掉潜在恶意数据以防止 SQL 注入(inject)的基本 C# 语法是:
System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection("SomeConnectionString")
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = "Insert Into tblExample (fldExample) Values (@fldExample)"; // Use a parameterized query to avoid SQL Injection
cmd.Connection = cn;
cmd.Parameters.AddWithValue("@fldExample", txtData.Text); // Set the value of the parameter to the value of the textbox.
// Use a try... catch...finally block to ensure the connection is closed properly
try
{
cn.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Item Inserted";
}
catch(Exception ex)
{
lblStatus.Text = ex.ToString();
}
finally
{
cn.Close(); // will happen whether the try is successful or errors out, ensuring your connection is closed properly.
}
请密切关注如何避免 SQL 注入(inject)。这非常重要,也是新开发人员经常错过的事情,因为他们和您一样,担心基本语法并使更新正常工作。您可以在没有参数化查询的情况下构建 SQL 语句,但最好立即学习它。
这是一篇关于参数化查询的文章。 http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
还有 OWASP 关于 SQL 注入(inject)的文章,您可以明白为什么我说它很重要。 (实际上,您应该熟悉 OWASP 网站和所有 OWASP Top 10,但本文与您的问题相关。) http://www.owasp.org/index.php/SQL_Injection
对于如何为 SQL Server 和其他数据库构建连接字符串的列表,我最喜欢的引用是 http://www.carlprothman.net/Default.aspx?tabid=81
关于c# - VIsual Studio WinForm 连接到 SQL Server 数据库 : C# syntax to transfer the data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4091735/