重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
Imports System.Data
梨林ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联建站的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!
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
1、打开代码窗口,添加引用:Imports System.Data.SqlClient。
2、输入以下代码:
“Public conn1 As SqlConnection = New SqlConnection _
("server=192.168.1.79; Initial Catalog= student; User ID= panqe;PWD=shentai768@")”,vb就已经成功连接sql数据库了。
3、代码详解:声明关键字Public(因为是全局变量,所以用Public 来声明)。
4、连接参数。
5、如果SQL 数据库就在本机,则用以下代码连接:
("server=.; Integrated Security=False;Initial Catalog= student; User ID= panqe;PWD=shentai768@")。
6:如果代码太长,影响可读性,可以用空格加"_"后,回车换行。
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
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)