一、开发环境
语言环境:Microsoft.NET Framework 4.6 SDK
IDE:Microsoft Visual Studio Community 2015
二、代码
Imports System.Data.SqlClient
Public Class Form1
'连接本机数据库并获取'test_one'数据库中的'sc'表数据
Dim mybind As BindingManagerBase
Dim myconn As New SqlConnection("Initial Catalog=test_one;Data
Source=localhost;Integrated Security=True;")
Dim myadapter As New SqlDataAdapter("select * from sc", myconn)
Dim mydataset As New DataSet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
myadapter.Fill(mydataset, "选课")
Me.DataGridView1.DataSource = mydataset.Tables("选课")
mybind = BindingContext(mydataset.Tables("选课"))
_display(1)
TextBox1.DataBindings.Add(New Binding("Text", mydataset, "选课.snum", True))
TextBox2.DataBindings.Add(New Binding("Text", mydataset, "选课.cnum", True))
TextBox3.DataBindings.Add(New Binding("Text", mydataset, "选课.score", True))
End Sub
Sub _display(ByVal index As Integer)
Me.TextBox1.Text = mydataset.Tables("选课").Rows(index).Item(0)
Me.TextBox2.Text = mydataset.Tables("选课").Rows(index).Item(1)
Me.TextBox3.Text = mydataset.Tables("选课").Rows(index).Item(2)
End Sub
'Button4 点击上移
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
mybind.Position = mybind.Position - 1
_display(mybind.Position)
End Sub
'Button5 点击下移
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
mybind.Position = mybind.Position + 1
_display(mybind.Position)
End Sub
'Button1 点击插入数据
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim mycmd As New SqlCommand
myconn.Open()
mycmd.Connection = myconn
mycmd.CommandText = "insert into sc values('" & TextBox1.Text & "','" &
TextBox2.Text & "'," & Val(TextBox3.Text) & ")"
MessageBox.Show(mycmd.CommandText)
Try
mycmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("insert failed")
End Try
myconn.Close()
End Sub
'Button2 点击删除数据
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
mybind.RemoveAt(mybind.Position)
End Sub
'Button6 点击更新数据
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Me.Validate()
mybind.EndCurrentEdit()
Dim cmd As New SqlCommandBuilder(myadapter)
myadapter.Update(mydataset.Tables("选课"))
End Sub
End Class
三、小结
相较于 Java 连接 MySQL、Oracle 等数据库时需要使用 JDBC 驱动,通过 ADO.NET 连接SQL Server 由于处于同 Microsoft 生态,其连接时较为方便,是由 ODBC 进行连接,而其相当于是提供了一组规范的接口,开发者无需关心连接细节,只需要根据规范编写相应的语句操作 SQL Server。ODBC(Open Database Connectivity,开放式数据库连接),是微软在 Windows 平台下推出的,使用者在程序中只需要调用 ODBC API,由 ODBC 驱动程序将调用转换成为对特定的数据库的调用请求