建立数据库连接后,可以进行数据库操作,基本的套路就是写SQL语句,然后执行。像建表、插记录、改记录这类操作,是不需要返回数据的,所以用.ExecuteNonQuery()方法,而查记录操作,是需要返回数据的,必须用.ExecuteReader()方法返回数据给一个数据读取对象,然后使用.Read()方法读取一条记录,继而根据类型读取相应的变量。
示例:
'建表
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
sqlcmd.CommandText = "CREATE TABLE TEST ( 工号 INT, 姓名 CHAR(10), 出生年月 DATETIME, 家庭住址 CHAR(100) )"
sqlcmd.ExecuteNonQuery()
End Sub
'插记录
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
sqlcmd.CommandText = "INSERT INTO TEST VALUES ( 1, '张三', '1983-3', '山东省青岛市')"
sqlcmd.ExecuteNonQuery()
End Sub
'改记录
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
sqlcmd.CommandText = "UPDATE TEST SET 家庭住址='山东省潍坊市' WHERE 姓名='张三'"
sqlcmd.ExecuteNonQuery()
End Sub
'查记录
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
sqlcmd.CommandText = "SELECT * FROM TEST"
sqlreader = sqlcmd.ExecuteReader
sqlreader.Read()
Label1.Text = "姓名:" & sqlreader.GetString(1) & vbCr & _
"工号:" & sqlreader.GetInt16(0) & vbCr & _
"出生年月:" & sqlreader.GetString(2) & vbCr & _
"家庭住址:" & sqlreader.GetString(3) & vbCr
End Sub