使用vb.net连接到数据库并执行命令。
发表于:2007-06-30来源:作者:点击数:
标签:
Imports System Imports System.Data@#引入数据类库 Imports System.Data.SqlClient@#引入SQL Server类库(用来访问SQL Server) Module Module1 Sub Main() AddRecord() @#增加记录 RemoveRecord() @#删除记录 Pause() End Sub Sub Pause() Console.WriteLine
Imports System
Imports System.Data @#引入数据类库
Imports System.Data.SqlClient @#引入
SQL Server类库(用来访问SQL Server)
Module Module1
Sub Main()
AddRecord() @#增加记录
RemoveRecord() @#删除记录
Pause()
End Sub
Sub Pause()
Console.WriteLine("Press Enter To Continue...")
Console.ReadLine()
End Sub
Sub AddRecord()
@#定义连接字符串
Dim sConnectionString As String _
= "User ID=sa;Initial Catalog=pubs;Data Source=(local)"
@#定义一个SQL连接对象
Dim objConn As New SqlConnection(sConnectionString)
@#连接对象
objConn.Open()
@#定义一个插入记录命令字符
Dim sSQL As String = "INSERT INTO Employee " & _
"(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _
"VALUES (@#MSD12923F@#, @#Duncan@#, @#W@#, @#Mackenzie@#, " & _
"10, 82,@#0877@#,@#2001-01-01@#)"
Dim objCmd As New SqlCommand(sSQL, objConn)
Try
objCmd.ExecuteNonQuery() @#执行插入动作
Catch e As Exception
Console.WriteLine(e.Message) @#无法执行时提示出错信息
End Try
Console.WriteLine("Record Added")
End Sub
Sub RemoveRecord()
Dim sConnectionString As String _
= "User ID=sa;Initial Catalog=pubs;Data Source=(local)"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id"
Dim objCmd As New SqlCommand(sSQL, objConn)
objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9)
objCmd.Parameters.Item("@emp_id").Value = "MSD12923F"
Try
objCmd.ExecuteNonQuery()
Console.WriteLine("Record Deleted")
Catch e As Exception
Console.WriteLine(e.ToString)
End Try
Console.ReadLine()
End Sub
End Module
原文转自:http://www.ltesting.net