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

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

Related

How to count tell if data already exist in a sql table using VB.net

I have a table that looks like thisTable When I use this code it works fine
Private Sub CountData()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=LVAPP; Initial Catalog=CFLineTracker;Persist Security Info=True;User ID=CFLineAdmin;Password=aaonunit#1"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT COUNT(*) FROM ItemDetails where ItemMasterId = " & IMID & ""
RD = cmd.ExecuteScalar
Label5.Text = RD
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
But when I try to run this code I get an exception
Private Sub CountData()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=LVAPP; Initial Catalog=CFLineTracker;Persist Security Info=True;User ID=CFLineAdmin;Password=aaonunit#1"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT COUNT(*) FROM ItemDetails where Serial Number = " & SN & ""
RDSN = cmd.ExecuteScalar
Label5.Text = RDSN
End Sub
The SQL Exception is:
Additional information: An expression of non-boolean type specified in
a context where a condition is expected, near 'Number'.
I'm using SQL SERVER 2008 R2 VB.net 2013

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

DB connection not open

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.

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

"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