Hi, I don't know how to make connection in visual basic and sql, but I am giving you the code to connect the visual basic .net with sql. Make use of it if you want.
This code will be added to module to connected sql server with vb.net:
Code:
Imports System.Data
Imports System.Data.SqlClient
Module Koneksi
Public con As SqlConnection
Public Function GetConnect()
con = New SqlConnection("server = MyServerName;database = MyDatabaseName;Trusted_Connection = yes")
Return con
End Function
End Module
Code to be placed in button click event:
Code:
Private Sub btnAdd_Click(ByVal send As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim test As Integer
Dim conn As SqlConnection
Dim cmdStud As New SqlCommand
Dim cmdStud1 As New SqlCommand
Dim daStudAs New SqlDataAdapter
Dim dsStudAs New DataSet
Dim dtStudAs New DataTable
If txtId.text = "" Or txtFirstName.Text = "" txtLastName.Text = "" Or txtAge.Text = "" Then
MsgBox("Student data wrong", MsgBoxStyle.OKOnly)
Else
If MsgBox("You really want to save dat with id : " & txtId.text & " ?", MsgBoxStyle.OKCancel, "Input confirm") = MsgBoxResult.Cancel Then
' do nothing
Else
conn = GetConnect()
conn.Open()
cmdStud = conn.CreateCommand
cmdStud.CommandText = "SELECT * FROM StudWHERE Id='" & Trim(txtId.text) & " ' "
daStudent.SelectCommand = cmdStud
daStudent.Fill(dsStudent, "Student")
dtStud= dsStudent.Tables("Student")
If (dtStudent.Rows.Count > 0) Then
MsgBox("Studdengan Id " & Trim(cmbId.Text) & " already in database", MsgBoxStyle.OKOnly, "Message :")
Else
cmdStud1 = conn.CreateCommand
cmdStud1.CommandText = "INSERT INTO Student(Id, FirstName, LastName,Age) VALUES('" & Trim(txtId.text) & "','" & Trim(txtFirstName.Text) & "','" & Trim(txtLastName.Text) & "','" & Trim(txtAge.Text) & "')"
test = cmdStud1.ExecuteReader.RecordsAffected()
If test > 0 Then
MsgBox("StudWith Id " & Trim(cmbId.Text) & " succesfully to added", MsgBoxStyle.OKOnly, "Message :")
Else
MsgBox("StudWith Id " & Trim(cmbId.Text) & " Failure to added", MsgBoxStyle.OKOnly, "Message :")
End If
Refresh_Form()
conn.Close()
End If
Catch ex As Exception
MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OKOnly, "Connection Error !!")
End Try
End If
End If
End Sub
Bookmarks