vb.net 操作数据库

======在窗体中添加DataGrid==========
 
Sub classquery()
        Dim str As String
        Dim ds As New DataSet
        Dim da As SqlDataAdapter

        str = "Data Source=localhost;Initial Catalog = Student;integrated Security=true"
        Dim con As New SqlConnection(str)
        con.Open()
        Dim sql As String = "select * from student_Info where 教室代码 = '" & TextBox1.Text.ToString().Trim() & "' "
        da = New SqlDataAdapter(sql, con)
        da.Fill(ds)
        DataGrid1.DataSource = ds.Tables(0)
    End Sub
======此方法是检验数据是否已存在============
 Sub singleYanzheng()
        Dim str As String
        str = "Data Source=localhost;Initial Catalog = Student;integrated Security=true"
        Dim con As New SqlConnection(str)
        con.Open()
        Dim sql As String = "select * from depart_Info where 系部ID='" & TextBox1.Text.ToString().Trim() & "' "
        Dim cmd As New SqlCommand(sql, con)
        Dim reader As SqlDataReader
        reader = cmd.ExecuteReader
        If reader.Read() = True Then
            MsgBox("该部门号已存在")
        Else
            addDepartInfo()
            MsgBox("success")
            clear()
        End If
    End Sub
========执行插入动作===========
 Sub addDepartInfo()
        Dim str As String
        str = "Data Source=localhost;Initial Catalog = Student;integrated Security=true"
        Dim con As New SqlConnection(str)
        con.Open()
        Dim sql As String = "insert into depart_Info(系部ID,系部名称,系主任) values('" & TextBox1.Text.ToString().Trim() & "','" & TextBox2.Text.ToString().Trim() & " ','" & TextBox3.Text.ToString().Trim() & "') "
        Dim cmd As New SqlCommand(sql, con)
        Try
            cmd.ExecuteNonQuery()  '执行SQL语句
        Catch e As Exception
            Console.WriteLine(e.Message) '无法执行时提示出错信息
        End Try
        Console.WriteLine("Record Added")
    End Sub

发布了25 篇原创文章 · 获赞 1 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章