简体   繁体   English

VB.Net与SQL通讯

[英]VB.Net and SQL Communication

I haven't done any serious programming in years, and I don't have much experience manipulating SQL data indirectly anyway, but I'm trying to create a program for my employer and running into confusion. 多年来,我没有做过任何认真的编程,而且我也没有太多间接地处理SQL数据的经验,但是我试图为我的雇主创建一个程序,并陷入混乱。 Many of the answers here and college books i have are helpful, but just when I think I understand what's going on, I get lost again, often because people use variables and column names that are identical, leaving it hard to figure out what is going where. 我在这里获得的许多答案和大学书籍都对您有所帮助,但是当我认为自己了解发生了什么时,我又迷失了,通常是因为人们使用相同的变量和列名,从而很难弄清发生了什么哪里。

So let's say I have a database called Attendance on SQL server localhost. 假设我在SQL Server本地主机上有一个名为Attendance的数据库。 Inside is a table called employees which consists of the columns: employee_id , name_last , name_first , and points . 内部是一个名为employees的表,该表包括以下列: employee_idname_lastname_firstpoints The first three are varchar and the last is a decimal(2,1) . 前三个是varchar ,最后一个是decimal(2,1) Using Visual Studio for Visual Basic, I've created a program which contains several textboxes. 使用Visual Studio for Visual Basic,我创建了一个包含几个文本框的程序。 The user enters the employee id which becomes var_empid when they hit the Load button. 用户输入单击“ 加载”按钮时将变为var_empid的员工ID。

How would I proceed so that the program executes an SQL query which pulls the name_last and name_first from the table where the employee_id matches the var_empid as input by the user and puts that data into the var_last_name and var_first_name variables? 我将如何继续执行程序,以便该程序执行一个SQL查询,该查询从employee_id与用户输入的var_empid匹配的表中提取name_last和name_first ,并将该数据放入var_last_namevar_first_name变量中?

Secondly, if the user entered into other textboxes information that became var_empid , var_last_name , var_first_name and then clicked the Add Employee button, how I would i proceed so that the information added by the user is written to the SQL table? 其次,如果用户在其他文本框中输入了变成var_empidvar_last_namevar_first_name ,然后单击“ 添加员工”按钮,我将如何进行处理,以便将用户添加的信息写入SQL表?

For clarification, moving data between textboxes and variables isn't the problem. 为了澄清起见,在文本框和变量之间移动数据不是问题。 I can do that all day. 我可以整天做。 It's moving the variables between the VB and SQL that is causing me problems. 它在VB和SQL之间移动导致我出现问题的变量。 I realize this is basic stuff, but any help would be great. 我意识到这是基本的知识,但是任何帮助都会很棒。

This is more than what you asked for, because I'm trying to push you into some good practices at the same time: 这超出了您的要求,因为我正试图同时将您带入一些良好实践中:

Public Class Employee
    Public Property ID As String 
    Public Property Points As Double 'why is this a decimal(2,1)?
    Public Property LastName As String
    Public Property FirstName As String

    Public Shared Function FromDataRow(ByVal data As IDataRecord) As Employee
         Dim result As New Employee()
         result.ID = CDbl(data("ID"))
         result.LastName = CStr(data("LastName"))
         result.FirstName = CStr(data("FirstName"))
         Return result
    End Function
End Class

Public Module DataLayer
    'Check www.connectionstring.com for more info on connection strings
    Private Property ConnectionString As String = "database connection string here"

    Private Iterator Function GetRecords(ByVal sql As String, ByVal addParams As Action(Of SqlParameterCollection)) As IEnumerable(Of IDataRecord)
        Using cn As New SqlConnection(ConnectionString), _
              cmd As New SqlCommand(sql, cn)

            addParams(cmd.Parameters)
            cn.Open()
            Using rdr As SqlDataReader = cmd.ExecuteReader()
                While rdr.Read)
                    Yield Return rdr
                End While
            End Using
        End Using
    End Function 

    Private Function GetRecords(Of T)(ByVal sql As String, ByVal addParams As Action(Of SqlParameterCollection), ByVal translate As Function(Of IDataRecord, T)) As IEnumerable(Of T)
       Return GetRecords(sql, addParams).Select(translate)
    End Function

    Public Function GetEmployeeData(ByVal EmployeeID As String) As Employee
        Dim sql As String = _
         "SELECT employee_id, name_last, name_first " & _ 
         "FROM employees " & _
         "WHERE employee_id= @ID"

        Return GetRecords(sql, _
            Sub(p) p.Add("@ID", SqlDbType.NVarChar, 10).Value = EmployeeID, _
            Employee.FromDataRow).First()
    End Function
End Class

To answer your second request, try to execute the following query: 要回答第二个请求,请尝试执行以下查询:

Dim Query = "INSERT INTO Attendance (name_first, name_last, points) VALUES(var_first_name, var_last_name, var_points)"

Note that i did not insert the var_empid because if you have created your table correctly, this id should be an auto-generated primary key that increments itself automatically. 请注意 ,我没有插入var_empid,因为如果正确创建了表,则此ID应该是自动生成的主键,该键会自动递增。

It's not easy to start because at first you see so many different names and technologies and they all seem to promise, more or less, the same thing. 开始并不容易,因为起初您会看到这么多不同的名称和技术,而且它们似乎或多或少都可以承诺同一件事。 Especially if you want to build a database-connected application, and start doing basic stuff like CRUD operations (inserts, updates, deletes...), it's easy to get confused. 尤其是如果您要构建连接数据库的应用程序,并开始进行诸如CRUD操作(插入,更新,删除...)之类的基本工作,很容易感到困惑。

Start reading here about ADO.NET Architecture . 从这里开始阅读有关ADO.NET Architecture的信息 You hopefully will understand something more about DataSet , Linq To SQL , Entity Framework , but probably not much. 希望您能对DataSetLinq To SQLEntity Framework有所了解,但可能不多。 This is why I strongly suggest to take a few days and slowly watch the tutorial videos by Beth Massi, on VB.Net and Data. 这就是为什么我强烈建议花几天时间并慢慢观看VB.Net和Data上Beth Massi的教程视频的原因。

On this page, How Do I Videos for Visual Basic , you will find a lot of useful information to start building simple but very effective applications and database. 在本页“ 如何为Visual Basic录制视频”上 ,您会发现许多有用的信息,可以开始构建简单但非常有效的应用程序和数据库。 Be sure to watch Forms over Data Video Series , Visual Basic 2008 Forms over Data Videos (using DataSets ) and then Language Integrated Query (LINQ) Series (using LINQ To SQL where you'll understand why in your vb.net application your object variables have the same name as your database columns). 确保观看数据视频系列上的表单,数据视频上的 Visual Basic 2008表单 (使用DataSets ),然后观看语言集成查询(LINQ)系列 (使用LINQ To SQL ,您将了解为什么在vb.net应用程序中使用对象变量与您的数据库列名称相同)。 FInally you can take a look at the Entity Framework tutorial (that you will find very similar to Linq To SQL). 最后,您可以看一下Entity Framework教程(您会发现它与Linq To SQL非常相似)。

After these basic tutorials you'll be able to choose your path and start programming. 在完成这些基本教程之后,您将能够选择自己的路径并开始编程。 Once you grasp the basic concepts it's a lot easier to search and understand what you find on the internet. 一旦掌握了基本概念,就可以轻松地搜索和了解在Internet上找到的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM