In our initial studies, VB and SQL Server are indispensable. So, how can we use VB to connect to the database? Today, we will solve this problem:
1. Use ADO (ActiveX Data objec, ActiveX Data Object) to connect to SQL
Server
1) Use the ADO control to connect
Use the connectionstring attribute of the ADO control to connect to the SQL
Server. This attribute contains a string of argument = value statements separated by semicolons. It is used to specify the information for establishing a connection to the data source. The syntax is as follows:
Provider=Drive;Password=UserPassword;PersistSecurity Info=False;User ID=UserName;Initial Catalog=Data Name;DataSource=ServerName
Example: Use the ADO control to connect to the database named student
PrivateSub Form_Load()Adodc1.connectionstring="Provider=SQLOLEDB.1;Password=;PersistSecurity Info=False;User ID=sa;Initial Catalog=student;Data Source=."End Sub
2) connect with An ADO object
ADO database access technology can be implemented not only through controls provided by VB, but also through ado-related objects. The ADO object includes the command object, connection object, recordset object, error object, Field object, parameter object, and property object. The connection object is used to manage the connection with the database.
Example: Use the open method of the connection object to connect to the database named student.
Dim cnn as ADODB.ConnectionPrivatesub Form_Load()set cnn=New ADODB.ConnectionCnn.open="provider=SQLOLEDB;password=;PersistSecurity Info=true;User ID=sa;Initial Catalog=student;Data Source=."End Sub
2. Use Dao (Data
Access Object, Data Access Object) connect to SQL Server
Use DAO to connect to SQL
The server can use the data control provided by VB to access SQL
Server, you must understand the connect attribute to define the type of the database to be connected. Because the data control uses access/jet as the data engine
You must use ODBC for indirect access to the server.
Set the string format when the connect attribute accesses ODBC:
ODBC;DataBase=DataName;UID=UserName;PWD-UserPassword;DSN=DataSourceName
Example: Use the data control to connect to the database named student through the studentinfo data source in ODBC
PrivateSub Form_Load()Data1.connect="ODBC;DataBase=student;UID=sa;PWD=123;DSN=studentinfo"End Sub
The above methods are applicable to SQL Server operations with VB. These methods may be easier to connect to the database than deplin or ASP. However, you only need to master these Connection Methods in your initial learning, easy to use.