VB.NET Cannot attach database query - sql-server-2008

I've a problem with connection VB.NET to Sql Server 2008 databases. I've already try to create a connection string and it still cannot attach and detect database query yet. It's show an error like this
This is my code I use:
Public Class Authentification
Private Sub Authentification_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
buka()
End Sub
Private Sub btlogin_Click(sender As System.Object, e As System.EventArgs) Handles btlogin.Click
Dim Sql, user, pass As String
user = txtusername.Text
pass = txtpassword.Text
koneksi.Close()
Call buka()
Sql = "SELECT * FROM tAdmin WHERE username = '" + user + "' AND password='" + pass + "'"
cmd = New SqlCommand(Sql, koneksi)
baca = cmd.ExecuteReader()
If baca.Hasrows = True Then
MenuUtama.Show()
Me.Hide()
Else
MessageBox.Show("Username atau password salah", "Konfirmasi", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtusername.Focus()
End If
txtusername.Text = ""
txtpassword.Text = ""
baca.Close()
cmd.Dispose()
End Sub
End Class
And this is the code for module buka:
Module Module1
Public koneksi As SqlConnection
Public data As DataSet
Public baca As SqlDataReader
Public adaptor As SqlDataAdapter
Public cmd As SqlCommand
Public ass As DataTable
Public str, sql As String
Public Sub buka()
str = "Data Source=DON-PC\SQLEXPRESS;Initial Catalog=dbFutsal;Persist Security Info=True;User ID=sa;Password=******"
koneksi = New SqlConnection(str)
Try
If koneksi.State = ConnectionState.Closed Then
koneksi.Open()
End If
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical, "Error")
End Try
End Sub
End Module
Can someone tell me what i'm wrong? Thanks before

Please check if you have the login user "sa" in your database. Also try removing "persist security info" from the connection string.

Firstly, probably not a good idea to publicly post your sa password.
But, let's keep it simple. Try this and see if it connects. if it doesn't work, please post error message.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conDB As New SqlClient.SqlConnection
Dim strConnectionString As String = "Data Source=ServerName;" & _
"Database=DatabaseName;" & _
"User Id=UserName;" & _
"Password=Password;" & _
"Connect Timeout=90;"
Debug.WriteLine(strConnectionString)
conDB.ConnectionString = strConnectionString
Try
conDB.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
' Do something
End Sub

Also, if this is not the same computer with the SQL database on it, try turning firewalls off and connecting again (on both the server and your client).

Only other thing I can suggest is to ensure you have the SQL Server Services running.
go to control Panel, Services, sort alphabetically and look for SQL Server. Start all services that aren't started already.

If it's a local db (like you said earlier) try Data Source=(local); instead of Data Source=DON-PC\SQLEXPRESS;

Related

vb.net cannot connect to sql server

I am trying to make a login database using vb.net. I am using this code to connect but it doesn't work!:
Public Class Form1
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = "Data Source=localhost; Initial Catalog=user; Integrated Security= true"
cmd.Connection = con
con.Open()
cmd.CommandText = "select login, password from auth where login= '" & TextBox1.Text & "' and password = '" & TextBox2.Text & "' "
rd = cmd.ExecuteReader
If rd.HasRows Then
Welcome.Show()
Else
MessageBox.Show("Login Failed", "error")
End If
End Sub
End Class
I have a data base on my sql server called "user" and in user there is a table named "dbo.auth". When I click Label2, visual basic says "con cannot be opened" I am using MySQL server workbench. Is there any way I can fix this? The server is also running on my local network.
Does this work for you?
Imports System.Data.SqlClient
Public Class LoginForm1
Dim conn As SqlConnection
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
conn = New SqlConnection
conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
Try
conn.Open()
MsgBox("Connected!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Also, I think you should bookmark the link below.
https://www.connectionstrings.com/

Why won't my .net application accept the SQL Query via user input?

I'm currently writing a quick .net program that will allow users to query a Database
I've got it working to a point where it'll run SELECT statements that are hardcoded but when I get the "sql" variable to look at the contents in a text box (user input) it chucks up an error. This happens even when I copy and paste a SQL Query that works hardcoded into the user text box
This is my code:
Imports MySql.Data.MySqlClient
Public Class form_queueDepth
Public dbconn As New MySqlConnection
Public sql As String
Public dbread As MySqlDataReader
Public dbcomm As MySqlCommand
Private Sub form_queueDepth_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbconn = New MySqlConnection("Data Source=10.232.7.41;user id=Alex;password=abc;database=alexvb")
Try
dbconn.Open()
MsgBox("Succeed")
Catch ex As Exception
MsgBox("Unable to connect: " & ex.Message.ToString)
End Try
End Sub
Private Sub button_ExecuteQuery_Click(sender As Object, e As EventArgs) Handles button_ExecuteQuery.Click
sql = "SELECT * FROM depth_store WHERE ID < '10';"
dbcomm = New MySqlCommand(sql, dbconn)
MsgBox(sql)
Try
dbread = dbcomm.ExecuteReader()
While dbread.Read
listBox_QueryResults.Items.Add(dbread("Queue_Manager").ToString() & " | " & dbread("Queue").ToString() & " | " & dbread("DTime").ToString() & " " & dbread("QueueDepth").ToString())
End While
MsgBox("Success")
Catch ex As Exception
MsgBox("Error: " & ex.Message.ToString)
End Try
End Sub
End Class
SO the above code will work but the moment i change "sql = "SELECT * FROM depth_store WHERE ID < '10';" to "sql = (textBox_UserQuery).ToString" and then copy & paste the query It chucks up an error stating:
http://i66.tinypic.com/2pqnxmo.png
Any suggestions/help would be much appreciated - Let me know if any you require any other information
textBox_UserQuery is the name of an instance of a TextBox.
The ToString() method returns the name of the class
IE: System.Windows.Forms.TextBox.
If you want to use the content of a TextBox you need the property Text.
sql = textBox_UserQuery.Text
Said that, I hope that this 'program' is only for your internal use. If not you are giving away the capability to destroy an entire database. (DELETE FROM .....)

update query not working when i attach the content of text box using data reader on page load

Code works fine when i remove the page load content. this is a form which will allow user to edit the data already present in database. i just want to let a user edit a form which he have already submitted.
This is the code:
Dim con As New SqlConnection("Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True")
Dim cmd, com As New SqlCommand
Dim dr As SqlDataReader
Dim n, d, a As Integer
Dim returnValue As Object
Dim str As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
str = "select * from School where RollNo=11"
com = New SqlCommand(str, con)
dr = com.ExecuteReader()
con.Open()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
con.Close()
dr.Close()
End Sub
Protected Sub Next_Click(sender As Object, e As EventArgs) Handles [Next].Click
Try
cmd.CommandText = "Update School SET RollNo='" & Enroll.Text & "', Name='" & Name.Text & "', Class='" & Class.Text & "' where RollNo=11 "
cmd.Connection = con
con.Open()
MsgBox("Connection is Open ! ")
n = cmd.ExecuteNonQuery
If n > 0 Then
MsgBox("data inserted successfully")
Else
MsgBox("data insertion failed")
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
con.Close()
End Try
End Sub
You have tagged your question with MySql but in code you use the classes for Sql Server and a connection string specific to Sql Server.
So you should clarify this point. However, in the meantime I wish to give an answer to some errors in your Page_Load event handler:
First you need to check if the call to Page_Load is a postback from other controls and avoid to reload the data from the database in that case. See ASP.NET Page Life Cycle
Second, open the connection before executing the reader
Dim constring = "Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str = "select * from School where RollNo=11"
If Not IsPostBack Then
Using con = new SqlConnection(conString)
Using cmd = new SqlCommand(str, con)
con.Open()
Using dr = com.ExecuteReader()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
End Using
End Using
End Using
End If
End Sub
As you can see there are other improvements: No more global variables for connection, command and reader and Using Statement around the disposable objects.
If this code is really intended to run against a MySql database then you need to use the appropriate classes like MySqlConnection, MySqlCommand, MySqlDataReader etc.. and fix the connectionstring

InvalidArgument=Value of '11209485' is not valid for 'index'. Parameter name: index error when running SQL query in VB.NET

I keep getting this error "Failure to communicate InvalidArgument=Value of '11209485' is not valid for 'index'. Parameter name: index" when I'm trying to retrieve card numbers from a database and put them in a combo box so that the user can pick their card number in VB.NET 2012. The 11209485 is the first card number in the database, so I assume the connection is fine, but I don't understand this error at all.
I'd be grateful for any help on the matter. Thanks!
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLcmd As MySqlCommand
Dim DataReader As MySqlDataReader
' load application Form
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Prepare connection and query
Try
dbCon = New MySqlConnection("Server=localhost;Database=***;Uid=***;Pwd=***")
strQuery = "SELECT CardNumber " &
"FROM Account"
SQLcmd = New MySqlCommand(strQuery, dbCon)
'Open the connection
dbCon.Open()
' create database reader to read information from database
DataReader = SQLcmd.ExecuteReader
' fill ComboBox with account numbers
While DataReader.Read
cboAccountNumbers = cboAccountNumbers.Items(DataReader("CardNumber"))
End While
'Close the connection
DataReader.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate" & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class
The error is in this line:
cboAccountNumbers = cboAccountNumbers.Items(DataReader("CardNumber"))
You are attempting to read the 11209485th item in the combo box and there aren't that many items. Try this instead:
cboAccountNumbers.Items.Add(DataReader("CardNumber"))

InvalidOperationException was unhandled - Easy fix?

Hi could someone please help me, I am a completely new to coding and just following material my teacher has given me.
I am currently making a vb programme connected to xampp-mysql database
I have made the login form where the user/pass is store on the xampp database. I have included some presence checks for the text boxes and now I am trying to implement a feature into my program where the user can change his/her password using their security passphrase.
My XAMPP database is called: ba-solutions
My table is called Login and my fields are Username, Password and Security
I tried looking online, but nothing makes sense or is relevant to me, but this maybe just because I don't understand it as I am new to coding.
I used the sheets from my teacher to write this code for the programme but when I try to run I get the error:
InvalidOperationException was unhandled
An error occurred creating the form. See Exception.InnerException for details. The error is: Format of the initialization string does not conform to specification starting at index 52.
Here is my all my code from my Login form:
Imports MySql.Data
Imports MySql.Data.MySqlClient
Module procedures_and_variables
Public objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password=")
Public objdataadapter As New MySqlDataAdapter
Public objdataset As DataSet
Public objcommandbuilder As New MySqlCommandBuilder
Public objdatatable As New DataTable
Public rowposition As Integer = 0
Public sqlstring As String
Public tablename As String
Public objcommand As MySqlCommand
Public reader As MySqlDataReader
Public database_path As String = "Server=localhost;database=ba-solutions;user id=root;password="
Public path As String
Public backup As New MySqlBackup
'Procedure which checks whether or not the current connection is open and opens it, if it is closed.
Public Sub connection_checker()
If objconnection.State = ConnectionState.Closed Then
Try
objconnection.Open()
Catch ex As MySqlException
MsgBox("Error connecting to database")
End Try
End If
End Sub
'Procedure which executes any SQL query.
Public Sub SQL_executer()
Call connection_checker()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = sqlstring
objcommandbuilder = New MySqlCommandBuilder(objdataadapter)
objdataadapter.Fill(objdatatable)
objdataadapter.SelectCommand.CommandType = CommandType.Text
End Sub
'Procedure used to load data from the database for the selected table.
Public Sub initial_load()
Call connection_checker()
Call SQL_executer()
objdataset = New DataSet
objdataadapter.Fill(objdataset, tablename)
objconnection.Close()
End Sub
'Procedure used to update data in a table with the changes made to the data in the datagrid.
Public Sub update_data()
Call connection_checker()
Try
objdataadapter.Update(objdataset, tablename)
MsgBox("Changes accepted", MsgBoxStyle.Information, "Update successfull")
Catch ex As Exception
MsgBox("Changes declined", MsgBoxStyle.Critical, "Update unsuccessfull")
End Try
End Sub
'Procedures used to bind the relevant data to the data grid, with the correct header titles.
Public Sub bind_dataset_client_details()
'NEEDS TO BE COMPLETED FOR ALL DATASETS
End Sub
End module
Public Class frmLogin
Dim form_type As Form
Dim user_table As String
Dim objconnection As New MySqlConnection("Server=localhost;database=ba-solutions;user id=root;password;")
Dim sqlstring As String
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
objconnection.Open()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = "Select * FROM Login"
End Sub
Private Sub Login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Login.Click
Me.Cursor = Cursors.WaitCursor
'Tries to open the server connection and it will give an error if connection fails.
Try
objconnection.Open()
Catch ex As Exception
MsgBox("Error connecting to database", MsgBoxStyle.Critical, "Database Error")
frmXampp.Show()
End Try
'Checks if the username textbox contains a value, if it does not, it creates an error provider.
If Len(txtUsername.Text) < 1 Then
MsgBox("You must enter a username.", MsgBoxStyle.OkOnly, "Login Error")
End If
'Performs same presence check as above on password textbox.
If Len(txtPassword.Text) < 1 Then
MsgBox("You must enter a password.", MsgBoxStyle.OkOnly, "Login Error")
End If
'SQL query
sqlstring = "SELECT * FROM Login Where username = '" + txtUsername.Text + "' AND password = '" + txtPassword.Text + "'"
'Creates command
objcommand = New MySqlCommand(sqlstring, objconnection)
'Executes command
reader = objcommand.ExecuteReader
'See if user exists
If reader.Read Then
MsgBox("Login Accepted!", MsgBoxStyle.Information, "Login Successful")
'Displays the Main Menu form after a successfull login
frmMainMenu.Show()
Me.Visible = False
Else
'And if authentication has failed, the user will be given an option to retry or exit
reader.Close()
Dim prompt As MsgBoxResult
prompt = MessageBox.Show("Invalid Username or Password. Please make sure your credentials are correct and try again or exit.", "Login Error",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning)
If prompt = MsgBoxResult.Cancel Then
Me.Close()
End If
End If
Me.Cursor = Cursors.Arrow
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Me.Close()
End Sub
Private Sub ForgotPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ForgotPassword.Click
Dim security, newpassword As String
security = InputBox("What is the security passphrase?")
sqlstring = "SELECT security FROM Login WHERE security = '" & security & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newpassword = InputBox("Enter new password")
sqlstring = "UPDATE 'Login' SET 'password' = '" & newpassword &
"' WHERE 'Login' . 'password' = '" & security & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Invalid Security Passphrase or New Password. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
End Class
Please bear in mind I am a complete newbie and I would really appreciate any help. Thank you.
I think you have an invalid connection string
Try this instead:
Server=localhost;Database=ba-solutions;Uid=root;