重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
dim
从事电信机房托管,服务器租用,云主机,雅安服务器托管,主机域名,CDN,网络代维等服务。
myselectquery
as
string
=
"select
*
from
表1
where
姓名='小强'"
dim
mycommand
as
new
sqlcommand
(myselectquery,
conn)
'建立一个command控件,conn是你的sqlconnection对象
conn.open()'打开数据连接
dim
myreader
as
sqldatareader'定义一个reader用来读数据
myreader
=
mycommand.executereader()'运行你的查询,结果到myreader
if
myreader.read()
then
'如果查到了数据
msgbox(myreader.getstring(0))
'显示第一个字段
end
if
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Inherits System.Windows.Forms.Form
'数据库连接对象
'错误的写法
'Dim objConnection As SqlConnection = New SqlConnection("server=(local);database=pubs;user id=sa;password=")
'正确写法
Dim objConnection As New SqlConnection("Data Source=127.0.0.1; Initial Catalog=pubs; user id=sa; password=;")
'数据适配器
Dim objDataAdapter As SqlDataAdapter = New SqlDataAdapter()
'DataSet
Dim objDataSet As DataSet = New DataSet()
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'设置查询命令属性
objDataAdapter.SelectCommand = New SqlCommand
objDataAdapter.SelectCommand.Connection = objConnection
objDataAdapter.SelectCommand.CommandText = "select au_lname,au_fname,title,price from authors join titleauthor on authors.au_id=titleauthor.au_id join titles on titleauthor.title_id=titles.title_id order by au_lname,au_fname"
objDataAdapter.SelectCommand.CommandType = CommandType.Text
'打开数据库连接
objConnection.Open()
'填充DataSet对象
objDataAdapter.Fill(objDataSet, "authors")
'关闭数据库连接
objConnection.Close()
'给DataGrid绑定数据
grdAuthorTitles.DataSource = objDataSet
grdAuthorTitles.DataMember = "authors"
'清除
objDataAdapter = Nothing
objConnection = Nothing
End Sub
End Class
VB.NET中有控件可以真接接点击属性进行连接配置.
SqlConnect数据连接控件.点击ConnectionString属性进行配置就可以了.
VB.NET中没有RecordSet了.取而代之的是DataSet.
在VB.net中可以先用SqlConnection对像来连接数据库再用SqlDataAdapter对像来读取数据并填充到DataSet里.然后就可以进行数据绑定了.
例:
dim
conn
as
SqlConnection
dim
da
as
SqlDataAdapter
dim
ds
as
Dataset
set
conn
=
new
SqlConnection
conn.ConnectionString="server=serverIP;database=databasename;uid=userid;pwd=password";
conn.open
da
=
new
SqlDataAdapter
(,conn)
da.fill(ds)
Public sqlcon As System.Data.SqlClient.SqlConnection
Public sqladapter As System.Data.SqlClient.SqlDataAdapter
Public command As System.Data.SqlClient.SqlCommand
Public ds As System.Data.DataSet
Public dr As System.Data.DataTable
sqlcon = New System.Data.SqlClient.SqlConnection
sqlcon.ConnectionString = "Server=(local); Initial Catalog=test1 ; User ID="数据库sa用户"; Password="数据库密码""
ds = New System.Data.DataSet
dr = New System.Data.DataTable(" test2 ")
ds.Tables.Add(dr)
sqladapter = New System.Data.SqlClient.SqlDataAdapter("select * from test2 ", sqlcon)
sqlcon.Open()
sqladapter.Fill(dr)
sqlcon.Close()
界面上控件
DataGridView1.DataSource = dr