此模块创建一个数据库,我需要一个语句才能使其通过单击按钮运行。
Module Module1
Sub Main()
' Define your connection string (update this based on your server and database)
Dim connectionString As String = ("Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;")
' Define the SQL command to create a new table
Dim createTableQuery As String = "
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY IDENTITY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
BirthDate DATE
)"
' Create and open a connection to SQL Express
Using connection As New SqlConnection(connectionString)
Try
' Open the connection
connection.Open()
' Create a command to execute the SQL query
Using command As New SqlCommand(createTableQuery, connection)
' Execute the command
command.ExecuteNonQuery()
Console.WriteLine("Table 'Employees' created successfully.")
End Using
Catch ex As Exception
' Handle any errors that may have occurred
Console.WriteLine("Error: " & ex.Message)
Finally
' Close the connection
connection.Close()
End Try
End Using
' Pause the console so you can see the result (only if you're using a Console App)
Console.ReadLine()
End Sub
End Module
我会将模块变成一个类,然后您可以创建一个对象并以这种方式执行代码。
它看起来像这样:
Public Class MyObject
Public Sub Main()
' Define your connection string (update this based on your server and database)
Dim connectionString As String = ("Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;")
' Define the SQL command to create a new table
Dim createTableQuery As String = "
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY IDENTITY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
BirthDate DATE
)"
' Create and open a connection to SQL Express
Using connection As New SqlConnection(connectionString)
Try
' Open the connection
connection.Open()
' Create a command to execute the SQL query
Using command As New SqlCommand(createTableQuery, connection)
' Execute the command
command.ExecuteNonQuery()
Console.WriteLine("Table 'Employees' created successfully.")
End Using
Catch ex As Exception
' Handle any errors that may have occurred
Console.WriteLine("Error: " & ex.Message)
Finally
' Close the connection
connection.Close()
End Try
End Using
' Pause the console so you can see the result (only if you're using a Console App)
Console.ReadLine()
End Sub
End Class
表格1:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Put any code here that when you start the program
End Sub
Private Sub CommandButton1_Click(sender As Object, e As EventArgs) Handles CommandButton1.Click
dim MyObject as new MyObject
MyObject.Main()
End Sub
End Class