DB connection not open - sql-server

i try this simple code with oledb connection but connection not open
Imports System.Data.OleDb
Public Class WebForm2
Inherits System.Web.UI.Page
Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=SQLOLEDB;Data Source=((localdb)\v11.0);Initial Catalog=test;User Id=MyUsername; Password=MyPassword;Integrated Security=SSPI;"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
i also try this connection string
connetionString = "Provider=SQLOLEDB;Data Source=test;Integrated Security=SSPI;"
same DB working well with sql client this connection string
Imports System.Data.SqlClient
Public Class WebForm2
Inherits System.Web.UI.Page
Dim globalp As String
Dim globals As String
Private strConn As String = "Data Source=(localdb)\v11.0;Initial Catalog=test;Integrated Security=True"
extra code not mention for simplicity of question.
any thing extra required so please mention in comments.
also another problem is that some told me that this issue arise due to SQL Server Authentication
i try to change security authentication mode in visual studio built in sql server but i don't get properties popup menu or right below in vs corner section of properties, from Object Explorer,
New error occur in this code section `Imports System.Data.OleDb
Public Class WebForm2
Inherits System.Web.UI.Page
Dim globalp As String
Dim globals As String
'Dim strConn As String = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=((localdb)\v11.0);Initial Catalog=test;Integrated Security=SSPI;"
Dim strConn As String = "Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;"
Dim conn As OleDbConnection
' Dim strConn As String = "Provider=SQLOLEDB; Data Source=(localdb)\v11.0; Initial Catalog=test; Integrated Security=SSPI"
' Private strConn As String = " Provider=Microsoft.Jet.OLEDB.4.0; Data Source=(localdb)\v11.0;Initial Catalog=test; User Id=MyUsername; Password=MyPassword"
' Private sqlCon As OleDbCommand
'Private strConn As OleDbCommand
'Provider=SQLOLEDB;
Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
If Page.IsValid Then
' cnn = New OleDbConnection(strConn)
' cnn.Open()
' MsgBox("Connection Open ! ")
' cnn.Close()
'sqlComm.CommandText = "sp1_userinformation"
' sqlComm.CommandType = CommandType.StoredProcedure
' sqlComm.Parameters.AddWithValue("UserName", name.Text)
' sqlComm.Parameters.AddWithValue("pass_word", fname.Text)
' sqlComm.Parameters.AddWithValue("CNIC", (cnic.Text))
' sqlComm.Parameters.AddWithValue("PartialAddress", (limitedtextarea.Text))
' sqlComm.Parameters.AddWithValue("Email", (email.Text))
' sqlCon.Open()
'lcit.Text = sname
' sqlComm.ExecuteNonQuery()
' Dim sname As String = name.Text
Dim sfname As String = fname.Text
Dim scnic As String = cnic.Text
Dim slimit As String = limitedtextarea.Text
Dim semail As String = email.Text
Dim stel As Int64 = Int64.Parse(tel.Text)
Dim stel1 As Int64 = 0 & stel
Dim query As String = String.Empty
Dim sdob As Date = Date.Parse(dob.Text)
query &= "INSERT INTO Userinfo (UserName, pass_word, CNIC, "
query &= " PartialAddress, Email, Telephone,DateOfBirth) "
query &= "VALUES (#colName,#colID, #colPhone, #colBranch,#colCourse,#coldblFee,#dobv)"
' query &= " PartialAddress, Email) "
' query &= "VALUES (#colName,#colID, #colPhone, #colBranch,#colCourse)"
' Using (sqlCon)
'sqlCon = New SqlConnection(strConn)
' Dim sqlComm As New SqlCommand()
' sqlComm.Connection = sqlCon
Using conn As New OleDbConnection(strConn)
Using comm As New OleDbCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#colName", username.Text)
.Parameters.AddWithValue("#colID", sfname)
.Parameters.AddWithValue("#colPhone", scnic)
.Parameters.AddWithValue("#colBranch", slimit)
.Parameters.AddWithValue("#colCourse", semail)
.Parameters.AddWithValue("#coldblFee", stel1)
.Parameters.AddWithValue("#dobv", sdob)
End With
' Try
conn.Open()
comm.ExecuteNonQuery()
' Catch(ex as SqlException)
'MessageBox.Show(ex.Message.ToString(), "Error Message")
' End Try
End Using
End Using
' End Using
End If
End Sub`
Error is (Must declare the scalar variable "#colName".)
error location comm.ExecuteNonQuery()

Try with SQL Server Native Client instead:
Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;
EDIT:
Your code would be:
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
Side Note: sql localdb does not work with SQL Server standard authentication, it only works with Windows integrated authentication.

OleDbCommand's use positional parameters and the question mark ? as the parameter marker, as oposed to SqlCommand's that use named parameters. So the sql statement should be:
INSERT INTO Userinfo
(
UserName, pass_word, CNIC, PartialAddress,
Email, Telephone, DateOfBirth
)
VALUES (?,?, ?, ?,?,?,?)
To add parameters to OleDbCommand.Parameters collection you don't need to change anything, you can use the parameter name you want as long as all parameter names are different. But rememeber, you need to add the parameters in order, because parameters are positional.

Related

Populate Combobox from SQL Server vb.net

I'm trying to populate a combobox with data from SQL Server. This is my code so far. There are asterisks around the errors. Also, ignore the comments.
Private Sub frmOriginal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim sqlcon As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
sql = "select * from TickerSymbol"
sqlcon = New SqlConnection(connetionString)
Try
sqlcon.Open()
command = New SqlCommand(sql, sqlcon)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
sqlcon.Close()
cboID.DataSource = ds.Tables(0)
cboID.ValueMember = "TickerSymbol"
cboID.DisplayMember = "TickerSymbol"
Catch ex As Exception
'MessageBox.Show("Can not open connection ! ")'
End Try
End Sub
Private Sub cboID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboID.SelectedIndexChanged
Dim dr As SqlDataReader
Dim command As New SqlCommand *(queryString, connection)*
Dim dataReader As SqlDataReader = command.ExecuteReader()
Dim sqlcon As SqlConnection
Dim cmd As SqlCommand
sqlcon = New SqlConnection
sqlcon.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
Try
sqlcon.Open()
cmd = New SqlCommand
cmd.CommandText = " select * from TickerSymbol where TickerSymbol = '" & cboID.Text & "'"
cmd = New SqlCommand(cmd.CommandText, sqlcon)
dr = cmd.ExecuteReader
While dr.Read()
'TxtID.Text = dr.GetInt32(0)'
'TxtSN.Text = dr.GetString(1)'
'TxtGender.Text = dr.GetString(2)'
'TxtPhone.Text = dr.GetInt32(3)'
'TxtAdrress.Text = dr.GetString(4)'
lblCompanyName.Text = dataReader.GetString(1)
lblPurchasePrice.Text = dataReader.GetSqlMoney(2)
lblQtyPurchased.Text = dataReader.GetInt32(3)
lblPurchaseDate.Text = dataReader.GetDateTime(4)
End While
sqlcon.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
sqlcon.Dispose()
End Sub
Please use parameterized queries as this will format values properly e.g. apostrophes in text will escape properly with parameters while without you must handle them, dates will be formatted properly too. Code is much cleaner also.
Example, syntax for Framework 3.5 and higher. If a connection string is used more than once then consider placing it in a private variable or under My.Settings under project properties.
Using cn As New SqlConnection With {.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"}
Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "select * from TickerSymbol where TickerSymbol = #TickerSymbol"}
cmd.Parameters.AddWithValue("#TickerSymbol", cboID.Text)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
'
'
'
End While
End If
End Using
End Using

I can't connect to my SQL Server database Using VB.NET

Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connString = "Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
sql = "select NET_ID, Password from User"
connection = New SqlConnection(connString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
I always get the msg box saying that connection can noy be established.
I tried to open SQL Server Management Studio at the same time the code running but I didn't anything.
From your exception text:
Incorrect syntax near the keyword 'User'
User is reserved keyword in SQL Server.
Basically not recommended to create table having name equals to reserved keywords, but if you really need this name, you have to surround it with square brackets in your query like this:
select NET_ID, Password from [User]
I from what I can see your connection string looks like it's creating the error you forget to escape the "\" character.
additional you can move code inside try block so that you get specific error code
so to escape you can change the line to become
connString = #"Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True";
OR
connString = "Data Source=.\\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True";
so update your code to become:
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
Try
connString = #"Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
//OR USE BELOW
//connString = "Data Source=.\\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
sql = "select NET_ID, Password from User"
connection = New SqlConnection(connString)
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connString = "Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
//Instead of
sql = "select NET_ID, Password from User"
//I used this
sql = "SELECT [NET_ID], [Password] FROM [User] "
And it worked
connection = New SqlConnection(connString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("~/Request/Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks everyone

Connecting a database to visual basic through code

i used this function to create a database:
Public Function CreateAccessDatabase (ByVal DatabaseFullPath As String) As Boolean
Dim bAns As Boolean
Dim cat As New ADOX.Catalog()
Try
Dim sCreateString As String
sCreateString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
DatabaseFullPath
cat.Create(sCreateString)
bAns = True
Catch Excep As System.Runtime.InteropServices.COMException
bAns = False
Finally
cat = Nothing
End Try
Return bAns
End Function
and i want to connect it through code, i tried this but it doesnt work:
Try
Dim constring As String
constring = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Utilizador.Utilizador-PC\Documents\Visual Studio 2013\Projects\WindowsApplication1\WindowsApplication1\Doc_Vendas_Cab.mdf;"
Dim conn As New SqlConnection(constring)
conn.Open()
MsgBox("Connected")
conn.Close()
Catch Ex As Exception
MsgBox(Ex)
End Try
how should i do it?
You are using ms-access database in you code why are you using SqlConnection provider it is for SQL server database.
You have to use OleDb.OleDbConnection provider.
See, this example link is helpful
Try
Dim constring As String
constring = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Utilizador.Utilizador-PC\Documents\Visual Studio 2013\Projects\WindowsApplication1\WindowsApplication1\Doc_Vendas_Cab.mdf;"
Dim conn As New OleDb.OleDbConnection(constring)
conn.Open()
MsgBox("Connected")
conn.Close()
Catch Ex As Exception
MsgBox(Ex)
End Try

How to check if a record exists in an Access database

I'm trying a new approach for a project that I'm working on and I'm just starting to learn about Access Databases. I using VB.net and my question is: How do you see if a record exists in the table of the database. I thought I had it understood but that is not the case. I'm creating a login and I want it to check if the Username that they typed in exists before it tries to compare what you typed with what's in the database. I see alot of questions on how to do this...but not for VB.net and MS Access
Here's my code:
Imports System.Data.OleDb
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & "' AND Password='" & PasswordTxt.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
myConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(sender As System.Object, e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
So now my question is... How do you get it to check if a record exists in the database, because when you type in the correct information (The correct username and password that exists in the database) it says welcome and all. But when you type in the wrong Username and/or Password it doesn't work. Without the "Try Catch" statement the program just freezes. With the try catch it states this:
System.InvalidOperationException: No data exists for the row/column.
at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.get_Item(String name)
at CybSol_Journal_Database.LoginForm1.AccessAccountDatabase() in c:\users\richard\documents\visual studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\LoginForm1.vb:line 36
Addition information: line 36 is this: If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
First problem:
PASSWORD is a reserved keyword in Access. You should encapsulate in square brackets:
"SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & _
"' AND [Password]='" & PasswordTxt.Text & "'"
Second problem:
NEVER use string concatenation to create sql text. ALWAYS use parameters
str = "SELECT * FROM Accounts WHERE Username=? AND [Password]=?"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("user", UserNameTxt.Text)
cmd.Parameters.AddWithValue("pass", PasswordTxt.Text)
dr = cmd.ExecuteReader
Why? look here what could happen if you concatenate strings from user input
Third problem: Test if your command returns rows
If dr.Read() Then
......
End if
I added some Using statements so you don't have to manually close the connections. Also, I parameterized the SQL statement to prevent SQL Injection.
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
'Public myConnection As OleDbConnection = New OleDbConnection
'Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
Using myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username=#USER AND [Password]=#PWD "
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#USER", UsernameTxt.Text)
cmd.Parameters.AddWithValue("#PWD", PasswordTxt.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
Else
MsgBox("Login Failure")
End If
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
You're on the right track. The OleDbDataReader.Read returns a boolean indicating whether or not it successfully read an existing row. Therefore, you can check to see if it returned True before trying to read the record. For instance:
If dr.Read() Then
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
End If
Also, I feel I should at least mention that storing a password in plain text is never a good idea.
You don't have to check for the username and password in your code again since if does not match in the database, no rows will be returned.
You can simply do
dr = cmd.ExecuteReader
If dr.HasRows Then
//it matched
Else
//it didn't match. could not log in
End If
Your approach is below if you still want to keep it but it's not necessary
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Else
End If
End If
Use the Read() method on your DataReader (note that this keeps your connection to the database open and you'll be unable to execute any other commands on the database while your DataReader is still Reading.
If String.Compare(dr("Username").ToString(), UsernameTxt.Text, true) AndAlso String.Compare(dr("Password").ToString(), PasswordTxt.Text.ToString() Then
' The username and password for the record match
' the input from the login form
ProcessLogin()
Else
' Invalid username or password, send an error
End If

"The ConnectionString property has not been initialized" error in VB.NET

Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
what can I do to solve this?
here are my codes
Module Module1
Function GetInfoForStudent(ByRef QueryName As String, ByVal UserName As String, ByVal Password As String) As DataTable
Using Con As New SqlConnection
Try
Using OleCon As New SqlConnection
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library
Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Con.Open()
Dim Cmd As SqlCommand = Con.CreateCommand()
Cmd.CommandType = CommandType.StoredProcedure
Cmd.CommandText = QueryName
Cmd.Parameters.AddWithValue("#user", UserName)
Cmd.Parameters.AddWithValue("#pass", Password)
Dim da As New SqlDataAdapter(Cmd)
Dim ds As New DataTable()
da.Fill(ds)
Return ds
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Using
End Function
End Module
Sub ShowStudentInfo()
Dim dt As DataTable = GetInfoForStudent("MyStoredProcName", "#user", "#pass")
' Since (presumably) only one is returned
With dt.Rows(0)
' Assign your text boxes
StudentIDTextBox.Text = .Item("StudentID")
LoginIDTextBox.Text = .Item("LoginID")
Student_NameTextBox.Text = .Item("Student Name")
Student_addressTextBox.Text = .Item("Student address")
End With
End Sub
You never assigned your connection string to the connection object, just like the error is saying.
Insert a line setting the connection string before con.open.
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)
You are creating the connection string object but never assigning it to your SqlCommand object.

Resources