连接数据库代码
OLEDB连接:(一)
Imports System.Data
Imports System.Data.OleDb
―――――――――――――――――
Private strcon As String = "Provider=SQLOLEDB.1;Data Source=(local);
Initial Catalog=数据库名;User ID=sa;Password=sa"
Public DBcon As New OleDbConnection(strcon)
Private ds As DataSet = New DataSet
Private sqlStr As String
―――――――――――――――――
DBcon.Open()
sqlStr = "select * from 表"
Dim adt As New OleDbDataAdapter(sqlStr, DBcon)
ds.Clear()
adt.Fill(ds)
Me.DataGrid1.DataSource = ds.Tables(0)
DataBind()
DBcon.Close()
―――――――――――――――――
(其中“DataBind()”可以没有,根据具体情况而定)
OLEDB连接:(二)
Imports System.Data
Imports System.Data.OleDb
―――――――――――――――――
Private strcon As String = "Provider=SQLOLEDB.1;Data Source=(local);
Initial Catalog=数据库名;User ID=sa;Password=sa"
Public DBcon As New OleDbConnection(strcon)
Private ds As DataSet = New DataSet
Private sqlStr As String
―――――――――――――――――
DBcon.Open()
sqlStr = "select * from 表"
Dim adt As New OleDbDataAdapter(sqlStr, DBcon)
ds.Clear()
adt.Fill(ds)
adt.ExecuteNonQuery()
DBcon.Close()
―――――――――――――――――
(其中“DataBind()”可以没有,根据具体情况而定)
SQL连接:
Imports System.Data
Imports System.Data.SqlClient
――――――――――――――――――
Private strcon As String = "Data Source=(local);Initial Catalog=EDUDB;
User ID=sa;Password=sa"
Public DBcon As New SqlConnection(strcon)
Private ds As DataSet = New DataSet
Private sqlStr As String
―――――――――――――――――
DBcon.Open()
sqlStr = " select * from 表 "
Dim adt As New SqlDataAdapter(sqlStr, DBcon)
ds.Clear()
adt.Fill(ds)
dg.DataSource = ds.Tables(0)
DBcon.Close()
------------------------------------
另一种连接方法:(SQL连接)
Imports System.Data
Imports System.Data.SqlClient
―――――――――――――――
Private conn As SqlConnection
Private cmd As SqlCommand
Dim conStr, sqlStr As String
conStr = "Data Source=数据源;Initial Catalog=数据库名;User ID=sa;Password=sa"
conn = New SqlConnection
conn.ConnectionString = conStr
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
――――――――――
sqlStr = "Insert into dbo.employee("
sqlStr = sqlStr & "ID,Name,BirthDate,Sex,Tel,HP,Address)"
sqlStr = sqlStr & "values("
sqlStr = sqlStr & "@ID,@Name,@BirthDate,@Sex,@Tel,@HP,@Address)"
――――――――――
cmd.CommandText = sqlStr