cara untuk menghubungkan visual basic dengan database ms sql server

32
Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server Jun 23, '08 2:00 AM for everyone Ada beberapa metode untuk menghubungkan Visual Basic dengan Database MS SQL Server saya akan memberikan penjelasan 2 metode diantaranya yaitu koneksi dengan menggunakan komponen DataEnvironment dan koneksi dengan menggunakan kode Program. untuk tutorial ini saya menggunakan Visual Basic 6 dan MS SQL Server 2000. 1. Koneksi menggunakan DataEnvironment 1. Buat Project Standard EXE 2. Klik menu Project | Add Data Environment, maka akan ditampilkan jendela Data Environment seperti ini : 3. Untuk membangun koneksi dengan Database SQL Server, Klik kanan objek Connection1 kemudian pilih Properties maka akan muncul jendela Data Link Properties. 4. Pada jendela Data Link Properties pilih driver untuk koneksi ke MS SQL Server, yaitu Microsoft OLE DB Provider for SQL Server. kemudian klik Next 5. Isi dengan nama server MS SQL Server kamu pada textbox "Select or enter a server name" (nama server adalah nama komputer kamu) 6. Pilih radio button "use a specific username and password" pada bagian 2.Enter information to log on to the server. 7. pada textbox username dan password isi dengan username dan password yang terdaftar di Database SQL Server kamu misalnya "sa" (user sa defaultnya tidak memiliki password). pada contoh ini saya menggunakan username 'yanadoe' dengan password 'bebas'. 8. sebagai tambahan, user sa adalah user yang mempunyai kewenangan penuh terhadap system di MS SQL Server atau disebut system administrator. user ini dibuat secara otomatis oleh MS SQL Server ketika proses instalasi. 9. setelah kamu lakukan langkah diatas, centang Checkbox "Allow saving password" agar kamu tidak perlu menginputkan lagi username dan password setiap kali aplikasi akan dijalankan. 10. Pilih database Northwind pada textbox "Select the database on the server". klik tombol Test Connection untuk mengetahui

Upload: subkhan-akbar

Post on 07-Apr-2015

3.011 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server Jun 23, '08 2:00 AMfor everyone

Ada beberapa metode untuk menghubungkan Visual Basic dengan Database MS SQL Server saya akan memberikan penjelasan 2 metode diantaranya yaitu koneksi dengan menggunakan komponen DataEnvironment dan koneksi dengan menggunakan kode Program. untuk tutorial ini saya menggunakan Visual Basic 6 dan MS SQL Server 2000.

1. Koneksi menggunakan DataEnvironment1. Buat Project Standard EXE 2. Klik menu Project | Add Data Environment, maka akan ditampilkan jendela Data

Environment seperti ini :

3. Untuk membangun koneksi dengan Database SQL Server, Klik kanan objek Connection1 kemudian pilih Properties maka akan muncul jendela Data Link Properties.

4. Pada jendela Data Link Properties pilih driver untuk koneksi ke MS SQL Server, yaitu Microsoft OLE DB Provider for SQL Server. kemudian klik Next

5. Isi dengan nama server MS SQL Server kamu pada textbox "Select or enter a server name" (nama server adalah nama komputer kamu)

6. Pilih radio button "use a specific username and password" pada bagian 2.Enter information to log on to the server.

7. pada textbox username dan password isi dengan username dan password yang terdaftar di Database SQL Server kamu misalnya "sa" (user sa defaultnya tidak memiliki password). pada contoh ini saya menggunakan username 'yanadoe' dengan password 'bebas'.

8. sebagai tambahan, user sa adalah user yang mempunyai kewenangan penuh terhadap system di MS SQL Server atau disebut system administrator. user ini dibuat secara otomatis oleh MS SQL Server ketika proses instalasi.

9. setelah kamu lakukan langkah diatas, centang Checkbox "Allow saving password" agar kamu tidak perlu menginputkan lagi username dan password setiap kali aplikasi akan dijalankan.

10. Pilih database Northwind pada textbox "Select the database on the server". klik tombol Test Connection untuk mengetahui apakah koneksi sudah berhasil atau tidak jika sukses klik tombol OK untuk menutup window dialog Data Link Properties

Page 2: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Setelah tahap diatas, koneksi dari Visual Basic ke Database MS SQL Server sudah terbentuk selanjutnya untuk mengambil data dari sebuah table di Database pertama kamu harus menambahkan sebuah Command pada DataEnvironment, Caranya sebagai berikut :

Mengambil Data dari Database

1. Klik kanan pada jendela DataEnvironment, pilih Add Command. maka akan dibuat

sebuah object dengan nama Command1 2. Klik kanan Command1, pilih Properties. setelah muncul jendela Command1 Properties,

pilih Table pada bagian Database Object, dan pilih sebuah table pada bagian Object Name misalnya table Customers. kemudian klik OK

Menampilkan Data dengan DataGrid

1. Pertama kamu harus menambahkan komponen DataGrid pada ToolBox caranya : klik menu Project | Components, pada jendela Components pilih Microsoft DataGrid Control 6.0

2. Setelah objek DataGrid ditambahkan pada Toolbox, klik komponen DataGrid tersebut kemudian Click and Drag pada Form1.

Page 3: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

3. Set Properties DataSource menjadi DataEnvironment1, dan Properties DataMember menjadi Command1

4. Klik kanan pada DataGrid, pilih Retrieve Fields klik OK pada Message Dialog yang muncul

5. Data pada table tidak akan langsung ditampilkan pada saat Design, untuk melihat datanya kamu harus Run Program dengan menekan F5.

2. Koneksi Menggunakan Kode Program

Pada metode yang kedua ini kita tidak akan menggunakan Komponen Visual untuk mengakses Database SQL Server dari Visual Basic. kita akan menggunakan kode program untuk melakukannya. inilah langkah-langkahnya :

1. Masuk ke Code Editor 2. Deklarasikan variabel untuk koneksi ke Database SQL Server

Public SQLServerConn As ADODB.Connection

3. Karena koneksi ke Database harus sudah tersedia ketika aplikasi akan dijalankan, maka kita harus menambahkan kode Program pada event OnLoad Form1. Caranya dobel klik Form1, kemudian tambahkan kode Program dibawah ini :

o Set variable SQLServerConn sebagai sebuah ADO Database Connection.

Set SQLServerConn = New ADODB.Connection

o Set Parameter String Koneksi variable SQLServerConn agar terhubung dengan Database SQL Server

SQLServerConn.ConnectionString = "Provider=SQLOLEDB.1;" & _

"Password=bebas;Persist Security Info=false;" & _

"User ID=yanadoe;Initial Catalog=Northwind;Data Source=siberat"

o Buka koneksi

SQLServerConn.Open

Coba kamu Stop Service Database SQL Server menggunakan SQL Server Service Manager, dan Run Porgram, maka akan tampil Error message seperti ini :

Page 4: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Kita akan menambahkan kode program untuk memeriksa status Service Database SQL Server apakah berjalan atau tidak. jika tidak maka akan ditampilkan error message versi kita jika service Database SQL Server tidak berjalan. untuk melakukannya, gunakan kode program dibawah ini :

On Error Resume Next

'memeriksa status Database

'pesan error yang akan muncul jika Database SQL Server

'dalam keadaan mati (service dalam status stop)

If Err.Number = -2147467259 Then

   MsgBox "Tidak dapat menghubungi Database SQL Server." & vbCrLf & _

   "Pastikan Service Database SQL Server sudah berjalan", vbCritical , "Koneksi Gagal"

   End     'Tutup Aplikasi

End If

Tips : Kamu bisa gunakan komponen ADODC untuk mendapatkan parameter ConnectionString seperti diatas, caranya sebagai berikut:

tempatkan sebuah komponen ADODC pada form Klik kanan, pilih ADODC Properties, Klik Build, akan muncul jendela Property Pages. Lakukan langkah 4 s/d langkah 10 pada Koneksi menggunakan DataEnvironment diatas.

setelah itu Copy string koneksi yang ada bagian "Use Connection String" jendela Property Pages. metode ini bisa juga digunakan untuk mendapatkan parameter ConnectionString untuk jenis Database yang lain

Itulah Tutorial singkat Pemrograman Visual Basic untuk menghubungkan Visual Basic dengan Database SQL Server. Semoga bermanfaat.

links:http://easycomputertutorial.blogspot.com/2008/05/beberapa-metode-untuk-menghubungkan.html

1. Dim cnCon As ADODB.Connection2. Dim rs As ADODB.Recordset

Page 5: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

3. Dim strSQL As String4.  5. Set cnCon = New ADODB.Connection6. Set rsProbe = New ADODB.Recordset7.  8. strSQL = "SELECT blah blah blah"9.  10. With cnCon11.     .Provider = "SQLOLEDB"12.     .Properties("Data Source") = "your sql server"13.     .Properties("User ID") = "your user id"14.     .Properties("Password") = "your password"15.     .Open16.     .DefaultDatabase = "your default database"17. End With18.  19. With rs20.      .ActiveConnection = cnCon21.      .CursorType = adOpenStatic22.      .CursorLocation = adUseServer23.      .LockType = adLockOptimistic24.      .Source = strSQL25.      .Open26. End With

LESSON 10 - Working with a database ...part 2Wednesday, April 07, 2010

For more information and special deals

related to any of the issues on this page,

place your cursor over the double-underlined

links. All information supplied

by Kontera.com.

Using multiple tablesOur ProjectMgt application contains an Employee table and a Department table linked through the employee's department number.

Page 6: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Now, if we create a form for Employee maintenance using the same technique we used in the previous lesson, we can access all fields in the Employee table using one data control, Data1. This is what the basic form will look like, before we get to put in the usual improvements:

Page 7: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

But suppose I want to select the employee's department from a list rather than keying in the department number.

For this we need a new control - it's called the DBList control. It's not in the standard toolbox, we have to get it.

For that: go to the menu bar -->Project -->Components -->Microsoft Data Bound List Controls 6.0 and put a check in the box then click OK.

Once you've done that two new controls appear in the toolbox.

Page 8: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Now to get the department names to appear in the list.

That means I will have to access the Department table, in addition to the Employee table.

Remember: you need one data control for every table you want to access.

Page 9: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

So first, create a second data control, Data2, on the form. It doesn't matter where we put it, we're going to make it invisible anyway.

Data2 has to have the same Connect property and the same DatabaseName as Data1 but, the RecordSource must specify: Department.

Now to get the list right.

First, we delete the department_number TextBox. Then we add a DBList.

Now we specify the DBList1 properties. Careful! This is where most people hit a snag!

The Data properties: these specify where the data entered will be stored. We are in the Employee table. That's Data1. So, the data entered will go into DataSource: Data1 and the field into which it is going is DataField: e-Dept.

The List properties: these tell the control where to get the information to show in the list. Since we want it from the Department table, we specify RowSource: Data2. What will appear in the list is the Department name so we choose ListField: d_Name. Finally, there has to be a link between Data2 and Data1. That is always the field which is the primary key in the list table and that is the BoundColumn: d_Number.

Page 10: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

And once everything is cleaned-up, the Data2 control is hidden, we get the final result:

Page 11: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

For additional resources you might find this site useful: Free Visual Basic 6 tutorials and sample source code examples .

9 - Working with a databaseWednesday, April 07, 2010

For more information and special deals

related to any of the issues on this page, place your cursor over the double-underlined links. All information

supplied by Kontera.com.

Page 12: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Creating the databaseIn the final 2 lessons in this tutorial, we will be developing a VB Project on "Project Management". The actual database we will be using has already been modelled and created in the tutorial on Database Design and SQL, Lesson 2.

If you haven't read it yet, you should read it now.

If you prefer, you can download the sample database to do the lessons: Download Project Management database.

The Project Management exampleezConsulting Inc. is a company doing IT systems consulting work with a large number of clients. At any given time there are dozens of projects on the go, each employing several employees. In a given period (in this case, weekly) an employee could work on several different projects. In order to track costs and revenues for each project, each employee will submit a timesheet every week showing the number of hours spent on each project. And, since all employees are attached to only one department, costs and revenues can be calculated by department.

It has already been determined that the ProjectMgt database will consist of the following tables:

Employees: details on every employee - ID, name, address, telephone, date hired, salary, chargeout rate, department

Projects: details of every project - project number, title, budget, start date, end date

Departments: lookup table of departments - number, name, head

Timesheets (Master/Detail): tables to store time spent on projects - date, employee, project, number of hours

The first task to be developed in the application consists of table maintenance. For each of the main tables, Employees, Projects and Departments, there have to be ways to add new records, remove records that are no longer needed and change records when appropriate. For example, new employees are hired and other employees leave, the name of a department is changed or a new project is started. Each of these maintenance operations will require a separate form.

Once the maintenance functions are in place, and they have to be (remember: referential integrity dictates that you can't accept a timesheet for a non-existant

Page 13: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

employee or non-existant project), we can start working on the operational functions, entering timesheets and producing reports. There will be forms for these tasks also.

To make it easier to access the different forms, we will create an Application Menu like we did in the previous lesson. The layout of the Menu form is standard and the code consists of a series of Load and Show statements for the various forms.

Top

Version problems

VB 6 and Access 2000 have compatibility problems. Because VB 6 was released before Access 2000, it does not normally recognize the Access 2000 format. In the example that follows, look at the Connect property of the Data control. If you don't have Access 2000 in the choices when you open "Connect", you have an older

Page 14: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

version of VB. If you try to connect to an Access 2000 database, you will get a message saying that you have an "Unrecognized database format". If you have an older version of VB6, you will have to get the fix for it. You may be aware that Microsoft regularly publish upgrades to their software products (not that they admit that there are problems with them!). Those upgrades are called Service Packs. Right now, Visual Studio (which includes Visual Basic) is at Service Pack 5. By the time you read this that may have changed. So, to fix your compatibility problem you will have to download the latest Visual Studio Service Pack from Microsoft.

There is a quick fix to the problem, which is what we've done here to save you the trouble of having to download. You can convert your Access 2000 database to Access 97 and use your old VB.

To do that in Access 2000, go to Tools -->Database utilities -->Convert and that will do the trick until you have the time to upgrade VB.

This will also come in handy later when we look at a VB Add-in called Visual Data Manager. Unfortunately, that Add-in does not work at all with Access 2000, even with the VB Service Pack. If you want to use it you will have to convert the database.

The Data ControlTo begin the application, we will first create a new form for Projects maintenance: ProjMaint.

The first control we will place on the form, once we've set the basic form properties and saved it, is called the Data Control. It is the object which links a form to a database and allows you to access the fields in the tables making up the database. It's called Data in the Toolbox.

VB provides other objects that allow you to link to databases. ADO (ActiveX Data Objects) are certainly more powerful and more efficient than the Data Control. However, they do require a lot more coding and are more difficult to implement. Also, they are not available in the Standard Edition of VB, only in the Professional and Enterprise Editions. In simple applications, the Data Control, slow as it is, gives you a tool that is easy to implement and will provide most of the functionality you need.

Page 15: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

The arrow buttons on the control are used to navigate through the database records:

     First record and Previous

     Next and Last record

The buttons correspond to 4 methods of the DC which you can use when you have to navigate using code. They are: MoveFirstMovePreviousMoveNextMoveLastLet's look at the important properties of the Data Control:

Name: the name to use in code - Data1 is default - eventually we'll have several data controls on the form - we'll call this one dta_proj.

Connect: the kind of database - in this case it's Access - could be Foxpro, dBaseIV, etc.

DatabaseName: the name and path of the database the control is connected to.

RecordSource: the name of the database table being used. BOFAction and EOFAction: action to take when trying to read before the

beginning of file or past the end of file - we'll look at those later. Recordset: this is a run time property, and it's an important one - it

represents the result of the query executed to the database - it contains all the records required by this Data Control - when you navigate through the

Page 16: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

database, you are actually navigating through the recordset, which is then mapped back to the database - that is why the methods of the Data Control refer to the Recordset property.

Next we add the controls needed to look at the fields in the records. In many instances we will need to make changes to the data. Therefore, we'll use a TextBox for each of the fields so that we can both diaplay and enter data as needed. Each TextBox will be a bound control, meaning that it is bound or tied to a specific field from the database. When we navigate through the database using the arrow buttons the content of each TextBox will always reflect the content of the current field. To bind the control to the database field we use its Data properties:

DataSource is the name of the Data Control - remember that the DC specifies the name of the database to use and the name of the table to access - tip: enter this one before the DataField.

DataField is the name of the field to bind - that field is selected from the content of the table.

Top

Notice that we've also added several buttons to the form. These buttons represent the most common actions we have to perform on the records.

Page 17: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Important note: when you work with bound controls you have to remember that every time you move off a record, the record is automatically modified in the database - every change you make to a TextBox is reflected immediately in the table. That is why there is no Update button - the function is done automatically.

The Reset button allows you to cancel any changes you may have made to the fields - if you modified information and then change your mind about updating it, the Reset will skip the automatic update and return the fields to their original state. This is a method of the Data Control object and is written as: dta_proj.UpdateControls

There are 2 ways to Add new records to the table:

in the Data Control, dta_proj, set the EOFAction property = 2 - this will allow the user to go to Last Record and do a Next, which will add a blank record to the table;

use the AddNew method of the Data Control, as in:

dta_proj.Recordset.AddNew

To Delete the current record, you must use the Delete method followed by a MoveNext to move off the deleted record: dta_proj.Recordset.Deletedta_proj.Recordset.MoveNext

Page 18: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Top

Validating dataBefore the data you are entering get permanently transfered to the database, you often want to make sure they are correct. That is called data validation. We look here at two simple ways of validating data.

Let's say that the specs for the Projects maintenance part of the application call for three verifications:

a budget amount must be entered;

the budget amount must not exceed $1,000,000 the project end-date cannot be earlier than the start-date.

For the first two we'll use the Validate event of the control. This event is triggered when the CausesValidation property in the TextBox is set to True. Before losing focus, the validation is done. The parameter assigned to the event when it is generated automatically (it's called Cancel) represents the KeepFocus property. If you set it to true in code when you encounter a validation problem, it keeps focus on the current control until the problem is corrected.

The second technique is to use the LostFocus event. When focus moves off the control, you do the validation. If there is an error, you evoke the SetFocus method to put focus back to the control with the error.

Top

Page 19: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Finding a specific recordWhen you navigate with the arrow buttons or the Move... methods you are necessarily moving one record at a time. Very often there is a need to access a specific record in the database. For example, it might be to change the ending-date for the project called "XYZ Corp. Payroll System".

In this example we assume that the search will be conducted on Project title. It could be on Number or End-date if necessary and it would just involve minor changes to the code. We also assume that the user does not want to enter the full project title and will only input the first few characters; we will therefore make use of the "Like" operator to match the recordset to the search string.

First, we create a new TextBox, called txt_findTitle, to enter the search string. We will give this TextBox the TabIndex 0 because we want it to be the first control read when we look at a record. As soon as we move off the TextBox, the LostFocus event is triggered and checks whether the user has entered a search string or not. If there is no input into the search string, the user can work with the current record in the form. If there is a search string specified, the appropriate record will be loaded into the form.

The FindFirst method of the DC will locate the first occurence in the recordset matching the "content" parameter. If there are more than one records that match, the user then navigates forward using the arrows. The format of the FindFirst method is: DataControl.Recordset.FindFirst "fieldname = 'searchstring'"

If the fieldname contains a string value, you have to use single quotes to name the

Page 20: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

searchstring; you can use the other comparison operators in place of the =.

This technique can be adapted to search any field in the recordset for a specific record. There are also FindNext, FindPrevious and FindLast methods for the Data Control recordset.

You might also want to visit this site for Free Visual Basic 6 tutorials and sample source code examples .

Page 21: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Mematikan Komputer dengan VB 6 dan Command Prompt 4:33 PM | Author: Sapta

Project kali ini yang kita buat yaitu program untuk shutdown komputer. Program kita ini akan

memanggil program shutdown.exe milik windows XP keatas. Anda bisa modifikasi program ini

sebagai sleep (timer) untuk mematikan komputer sesuai keinginan anda. Untuk itu, ikuti

langkah berikut ini:

1. Bukalah program Visual Basic 6 anda dan buatlah Project baru dengan 1 form

2. Isikan command button dengan name : cmdMatikanKomputer dan captionnya Matikan

Komputer dan width button menyesuaikan panjang captionnya.

3. Isikan coding berikut pada cmdMatikanKomputer dengan menekan F7

Private Sub cmdMati_Click()

Shell "shutdown.exe -s -t 10 -f ", vbHide

End Sub

Lalu simpan project anda dengan menekan ctrl+S, kemudian run dengan menekan F5. Jika

anda mengklik tombol Matikan Komputer, maka program anda akan langsung mengeksekusi

shutdown.exe milik windows.

Berikut penjelasan dan parameter tentang pemakaian shutdown.exe :

- shutdown.exe [spasi] -i artinya menampilkan GUI dan paramter ini harus pertama ditaruh

- shutdown.exe [spasi] -l artinya log off (tidak bisa dengan pilihan -m )

- shutdown.exe [spasi] -s artinya shutdown

- shutdown.exe [spasi] -r artinya shutdown dan restart komputer

- shutdown.exe [spasi] -s artinya gagalkan shutdown

- shutdown.exe [spasi] -m \\namakomputer artinya remote shutdown komputer lainnya

- shutdown.exe [spasi] -t dd artinya shutdown komputer dengan waktu detik

- shutdown.exe [spasi] -c artinya shutdown dengan mengisi komentar maksimum 127 char

- shutdown.exe [spasi] -f artinya shutdown dengan mematikan aplikasi yang lagi jalan

Anda juga bisa memakai shutdown.exe dengan masuk ke command prompt lalu ketikkan

shutdown.exe -s -f -t 10 -c "komputer anda akan mati"

Page 22: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Sekian dan terimakasih.

'Code by Roy Strickland, submitted by Jarret Peterson

'This code can share

and unshare the directory

'c:\dos'

'===================================

'start a new project and

add three command buttons

'set forms AutoRedraw property to true

'ADD TO A

MODULE IN YOUR PROJECT:

'====================================

Option

Explicit

Public Platform As Long 'Platform ID of OS. 1 or 2

'Structure

for Getversion

Public Type OSVERSIONINFO

dwOSVersionInfoSize As

Long

dwMajorVersion As Long

dwMinorVersion As Long

dwBuildNumber As

Long

dwPlatformId As Long

szCSDVersion As String * 128 ' Maintenance

string for PSS usage

End Type

Page 23: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Public Const STYPE_DISKTREE As Long =

0

Public Const STYPE_PRINTQ As Long = 1

Public Const STYPE_DEVICE As Long

= 2

Public Const STYPE_IPC As Long = 3

'Access types

Public Const

ACCESS_READ As Long = &H1

Public Const ACCESS_WRITE As Long =

&H2

Public Const ACCESS_CREATE As Long = &H4

Public Const

ACCESS_EXEC As Long = &H8

Public Const ACCESS_DELETE As Long =

&H10

Public Const ACCESS_ATRIB As Long = &H20

Public Const

ACCESS_PERM As Long = &H40

Public Const ACCESS_ALL As Long =

&H7F

Public Const WNTYPE_DRIVE As Long = 1

Public Const

SHI_USES_UNLIMITED As Long = -1

'Info structures for NetShareAdd

Type

SHARE_INFO_2

shi2_netname As String * 14

shi2_type As Long

shi2_remark

Page 24: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

As String 'Far pointer to string

shi2_permissions As Long

shi2_max_uses As

Long

shi2_current_uses As Long

shi2_path As String 'Far pointer to

string

shi2_passwd As String * 10

End Type

Type

SHARE_INFO_50

shi50_netname As String

shi50_type As String

shi50_flags

As Long

shi50_remark As String

shi50_path As String

shi50_rw_password

As String

shi50_ro_password As String

End Type

'ACL for Security

Descriptor

Public Type ACL

AclRevision As Byte

Sbz1 As Byte

AclSize

As Integer

AceCount As Integer

Sbz2 As Integer

End

Page 25: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Type

'Security Descriptor for SHARE_INFO_502

Public Type

SECURITY_DESCRIPTOR

Revision As Byte

Sbz1 As Byte

Control As

Long

Owner As Long

Group As Long

Sacl As ACL

Dacl As ACL

End

Type

Type SHARE_INFO_502

shi502_netname As String

shi502_type As

Long

shi502_remark As String

shi502_permissions As Long

shi502_max_uses

As Long

shi502_current_uses As Long

shi502_path As String

shi502_passwd

As String

shi502_reserved As Long

shi502_security_descriptor As

SECURITY_DESCRIPTOR

End Type

Public Security As

Page 26: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

SECURITY_DESCRIPTOR

Public Declare Function GetVersionEx Lib "kernel32"

Alias "GetVersionExA" _

(lpVersionInformation As OSVERSIONINFO) As

Long

Public Declare Function lstrcpy Lib "kernel32" _

(ByVal lpString1 As

Any, ByVal lpString2 As Any) As Long

'NT

Public Declare Function

NetShareDelNT Lib "netapi32.dll" Alias "NetShareDel" _

(ByVal servername As

Any, ByVal netname As String, ByVal reserved As Long) As Long

Public Declare

Function NetShareAddNT

Lib "netapi32.dll" Alias "NetShareAdd"

_

(ByVal servername As Any, ByVal slevel As Long, _

buf As SHARE_INFO_502,

ByVal cbbuf As Long) As Long

'9x

Public Declare Function NetShareDel9x Lib

"svrapi.dll" Alias "NetShareDel" _

(ByVal servername As Any, ByVal netname As

String, ByVal reserved As Long) As Long

Public Declare Function NetShareAdd9x

Lib "svrapi.dll" Alias "NetShareAdd"

_

(ByVal servername As Any, ByVal slevel As Long, buf As SHARE_INFO_50, ByVal

cbbuf As Long) As Long

Page 27: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

'====================

'ADD CODE TO

FORM:

'====================

Option Explicit

Dim SI2 As

SHARE_INFO_2

Dim SI502 As SHARE_INFO_502

Dim SI50 As SHARE_INFO_50

Dim

OSVERInfo As OSVERSIONINFO

Dim ShareRemark As String

Dim SharePath As

String

Dim nerr As Long

Dim nPath As String

Dim pwd As String

Dim

ret As Long

Dim OS As Long

Private Sub

Form_Load()

OSVERInfo.dwOSVersionInfoSize = Len(OSVERInfo)

OS =

GetVersionEx(OSVERInfo)

Command1.Caption = "Create Share

NT"

Command2.Caption = "Create Share Win9x"

Command3.Caption = "Delete

Share"

End Sub

Private Sub Command1_Click()

'NT

On Error Resume

Page 28: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

Next

SetStrings

nerr = NetShareAddNT(0&,

2, SI502, ret)

Print nerr

End Sub

Private Sub

Command2_Click()

'9x

On Error Resume Next

SetStrings

nerr = NetShareAdd9x(0&,

50, SI50, ret)

Print nerr

End Sub

Private Sub

Command3_Click()

'Delete

On Error Resume Next

If OSVERInfo.dwPlatformId

= 1 Then

nerr = NetShareDel9x(0&, nPath, 0&)

Else

nerr =

NetShareDelNT(0&, nPath, 0&)

Print nerr

End If

End

Sub

Public Sub SetStrings()

If OSVERInfo.dwPlatformId = 1 Then

'9x

OS

nPath = "NewShare"

Page 29: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

ShareRemark = "Remark for new share"

SharePath =

"C:\dos"

pwd = "Share"

SI50.shi50_netname = nPath

SI50.shi50_path =

SharePath

SI50.shi50_remark = ShareRemark

SI50.shi50_type =

STYPE_DISKTREE

SI50.shi50_ro_password = vbNullChar

SI50.shi50_rw_password

= vbNullChar

Else

'NT OS

nPath = StrConv("NewShare",

vbUnicode)

ShareRemark = StrConv("Remark for new share",

vbUnicode)

SharePath = StrConv("C:\dos", vbUnicode)

pwd = StrConv("Share",

vbUnicode)

SI502.shi502_current_uses = 0

SI502.shi502_max_uses =

10

SI502.shi502_netname = nPath

SI502.shi502_passwd =

pwd

SI502.shi502_path = SharePath

SI502.shi502_permissions =

Page 30: Cara Untuk Menghubungkan Visual Basic Dengan Database MS SQL Server

ACCESS_ALL

SI502.shi502_remark = ShareRemark

SI502.shi502_reserved =

0

SI502.shi502_security_descriptor = Security

SI502.shi502_type =

STYPE_DISKTREE

End IfEnd Sub