1

I'm trying to connect to a SQL database within my vb.net form.

I usually connect to SQL using a .bat file which looks something like the following:

Runas /netonly /user:domain\ username "C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe"

I found a similar question here

I've searched for the vb.net alternative but I can't anything other than that.

My code look something like

Imports System.Data.SqlClient

Public Class Form1

Dim con As SqlConnection = New SqlConnection("Server= ;Database= ;User Id= ; Password= ")
Dim cmd As SqlCommand = New SqlCommand("Select top 1 from table (NOLOCK)")

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    If con.State = ConnectionState.Closed Then con.Open()
    Dim sdr As SqlDataReader = cmd.ExecuteReader()
    While sdr.Read = True
        MessageBox.Show(sdr.Item("Column1") & " " & sdr.Item("Column2"))
    End While
    sdr.Close()

End Sub
End Class

I get an error due to invalid user when I fill me details in.

Any help would be greatly appreciated.

Sorry if I've not done this correctly, long time lurker first time poster

Thanks

Community
  • 1
  • 1
LewisHill
  • 33
  • 1
  • 5

1 Answers1

0

Batch command is using the windows credentials to connect to the database server. To establish the trusted connection from your application both (application+ database server) must be in same domain or impersonated with it.

Create the connection for windows authentication like this

Dim con As SqlConnection= New SqlConnection("Data Source=server; Initial Catalog=DatabaseName; Integrated Security=SSPI;");

Put your exe at the system in same domain and can run successfully.

Also you can refer this Connection Strings for various connection strings.

Sandeep Kumar
  • 783
  • 1
  • 5
  • 13
  • Thanks for the reply Sandeep, the reason I use the batch command is because the DB and my PC are on different domains so my Windows credentials are different from my DB credentials. I did however try your suggestion and i get 'Login Failed. The login is from an untrusted domain and cannot be used with Windows authentication.' – LewisHill Jun 10 '14 at 13:15
  • Hi Lewis.. Sorry for delay reply. I tried this but didn't find any option to connect sql with windows authentication with different domain.Since windows authentication is trusted so the application should be in same domain or we should have facility to run it as... option to run it with domain's credentials. Press shift and right click on it.. Select run as different user. Now enter your domain's credentials where sql server exists. it should work. – Sandeep Kumar Jun 13 '14 at 16:31
  • Using Run as different user it will not work if you are outside the domain chosen in the credentials (outside the AD). – Sergio Rezende Jul 20 '23 at 00:24