i am trying to use an input from the user as part of a connection string to a SQL database - sql

my connection string is saved in a string variable names str
what i am trying to do is use an input from the user as part of the string
the parts i want to take from the user are the ID and PASS
i am simply trying to check the connection statues with the ID and the PASS as inputs from the user.
Dim str As String = "Data Source=DESKTOP;uid=ID;pwd=PASS;database=DB"
Dim conn As New SqlConnection(str)
Private Sub btnconnect_Click(sender As Object, e As EventArgs) Handles btnconnect.Click
PW = txtadminpass.Text
Try
conn.Open()
conn.Close()
MsgBox("GOOD")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
i haven't had much like while using the + and & for the strings.
any help would be appreciated.

The SqlConnectionStringBuilder is an appropriate class to use in this case. You can add parts of the connection string to it via properties, so there is no chance of making mistakes:
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim csb As New SqlConnectionStringBuilder
csb.DataSource = "DESKTOP"
csb.InitialCatalog = "DB"
csb.UserID = "z"
csb.Password = "x"
' output "Data Source=DESKTOP;Initial Catalog=DB;User ID=z;Password=x" '
Console.WriteLine(csb.ToString())
Console.ReadLine()
End Sub
End Module

So, you need to check if the user is allowed to log into the database or not. The way you have followed looks good, you define the connection string based on the given ID and password, and you try to establish a connection, if it fails, the user can't log in, else he can do that.
However, the way you defined the string is wrong, you must use concatenation to preserve the ID and password values, try this,
Dim str As String = "Data Source=DESKTOP; uid=" & ID & "; pwd=" & PASS & ";database=DB"

Another way, which makes it easy to read:
Const CONN_STRING As String = "Data Source=DESKTOP;uid={0};pwd={1};database=DB"
Dim connString As String = String.Format(CONN_STRING, txtUserID.Text.Trim, txtPassword.Text)

Related

the connectionstring property has not been initialized in vb.net

Everytime I click the button where the sub procedure execute, I'm getting the error "the connection string property has not been initialized"
Here is my code
Sub CheckExistingExp()
Dim aexpcheckifexisting As New DataSet
Dim bexpcheckifexisting As New OleDb.OleDbDataAdapter
Dim sqlcheck As String
Dim duplicateexp As Integer
sqlcheck = "select count(exp_doc) vcount from csap_exph where exp_doc = '" & RQuote(txtExpDoc.Text) & "' and status = 'A'"
bexpcheckifexisting = New OleDb.OleDbDataAdapter(sqlcheck, con)
bexpcheckifexisting.Fill(aexpcheckifexisting, "checkduplicateexp")
duplicateexp = aexpcheckifexisting.Tables("checkduplicateexp").Rows(0).Item("vcount")
If duplicateexp > 0 Then
If MsgBox("Expense Doc is already existing, are you sure you want to tag it as posted?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Approve_Expense()
Else
con.Close()
End If
End If
End Sub
What should I do to solve this?
Thanks.
Let alone the connection string which is missing, where did you open con for you to close it? [con.open()] and if your user hits MsgBoxResult.Yes your connection would stay open cause con.Close() is only called if duplicateexp <= 0.
dispose your con at the end of your code or use using which closes it automatically and use a try-catch to catch any errors.
have your connection string somewhere in app.config or make it public in a class or module or whatever you prefer and make your string = that value and open your connection at the beginning of the sub.

Need help extracting variables from a While Loop in VB.Net

I'm a novice with my coding so forgive me if my question seems basic but I'm having some trouble extracting my variables from this While Loop in order to then use the results of my SQL query for validation.
This script below is the event handling for a login button on an .aspx form processing an email and login field that will be listed in a correlating MSSQL database:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
Dim Column1 As String
Dim Column2 As String
Dim SQL = "SELECT * FROM Logins WHERE Email='" & email.Text & "' AND Password='" & password.Text & "'"
Dim oSqlDataReader As System.Data.SqlClient.SqlDataReader = Nothing
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
oSqlConnection.Open()
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(SQL, oSqlConnection)
oSqlDataReader = oSqlCommand.ExecuteReader
While oSqlDataReader.Read
Column1 = oSqlDataReader(name:="Email")
Column2 = oSqlDataReader(name:="Password")
End While
End Using
oSqlConnection.Close()
End Using
If "Column 1 etc."
End if
End Sub
End Class
As far as I can tell my code is working with no errors but every time I try and create an If statement my Variable Column 1 and Column 2 are undeclared making them useless.
If anyone could help with the correct layout for my code or missing areas and an explanation as to where I've gone wrong that'd be great.
If you move the If block inside the loop, do you get closer to the behaviour that you're expecting?
Protected Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
Dim Column1 As String
Dim Column2 As String
Dim SQL = "SELECT * FROM Logins WHERE Email='" & email.Text & "' AND Password='" & password.Text & "'"
Dim oSqlDataReader As System.Data.SqlClient.SqlDataReader = Nothing
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
oSqlConnection.Open()
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(SQL, oSqlConnection)
oSqlDataReader = oSqlCommand.ExecuteReader
While oSqlDataReader.Read
Column1 = oSqlDataReader(name:="Email")
Column2 = oSqlDataReader(name:="Password")
If "Column 1 etc....."
End if
End While
End Using
oSqlConnection.Close()
End Using
End Sub
It could be that your query is returning no rows or that the values returned are dbNull or nothing. I would check the data getting returned and error if appropriate.
Try running the query against the database directly. Are you getting a row back?
To avoid the error, you can declare the string as String.empty
Dim Column1 As String = String.empty
Or, when using it in the if statement check for nothing:
If Column1 Is Not Nothing AndAlso ...
Do not use string concatenation to build your sql query. Instead use sql-parameters to prevent sql injection and other issues.
I must admit that i don't know this syntax: oSqlDataReader(name:="Email"). Use following:
Dim email As String
Dim password As String
Dim sql = "SELECT * FROM Logins WHERE Email=#Email AND Password=#Password"
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(sql, oSqlConnection)
oSqlCommand.Parameters.Add("#Email", SqlDbType.VarChar).Value = email.Text
oSqlCommand.Parameters.Add("#Password", SqlDbType.VarChar).Value = password.Text
oSqlConnection.Open()
Using oSqlDataReader = oSqlCommand.ExecuteReader()
If oSqlDataReader.Read() Then
Dim emailColIndex = oSqlDataReader.GetOrdinal("Email")
Dim pwdColIndex = oSqlDataReader.GetOrdinal("Password")
email = oSqlDataReader.GetString(emailColIndex)
password = oSqlDataReader.GetString(pwdColIndex)
End If
End Using
End Using
End Using ' oSqlConnection.Close() not needed with using '
If email IsNot Nothing AndAlso password IsNot Nothing Then
End If
But instead of initializing two string variables you should implement a Login class that you can initialize and return from the method. You don't want to know the email and the password since you already have them.
Since this is ASP.NET i suggest to look at the available membership provider which are powerful and have a learning curve, but it's definitely worth the time.

VB.net Query wont retrieve data from access database

I have created a query using vb.net with parameters which should allow the query to retrieve data from my access database but however when I click on the button it only shows blank fields but no rows are retrieved from the database. Could you please help me what I am currently doing wrong.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Try
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT Route.RouteName + ', ' + Cruise.CruiseID As CruiseRoute FROM Route INNER JOIN Cruise ON Route.RouteID = Cruise.RouteID WHERE CruiseID = ?"
Dim cmd As New OleDbCommand(CruiseQuery, cn)
'cmd.Parameters.AddWithValue("CruiseID", OleDbType.Numeric).Value = Route_Txt.Text
cmd.Parameters.AddWithValue(("CruiseID"), OleDbType.Numeric)
Dim reader As OleDbDataReader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "RouteName"
While reader.Read
Dim rID As String = reader("RouteID").ToString()
cmd.Parameters.AddWithValue("?", rID)
row = reader("CruiseID") & "," & ("RouteName")
RCTable.Rows.Add(row)
End While
reader.Close()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
If the user enters route name in the text box then the rows should show cruise ID and route name for each of the selected routes. for example if users enters Asia in the text box, clicks on the button then the query should return the cruiseID for the cruises which are going to Asia.
Your use of parameters makes no sense. First you call AddWithValue and provide no value, then you execute the query and then you start adding more parameters as you read the data. Either you call AddWithValue and provide a value, or you call Add and then set the Value on the parameter object created. Either way, it MUST be before you execute the query or it's useless.
myCommand.Parameters.AddWithValue("#ParameterName", parameterValue)
or
Dim myParameter = myCommand.Parameters.Add("#ParameterName", OleDbType.Numeric)
myParameter.Value = parameterValue

Use the value an XML element as a variable for a procedure

I am new to working with XML in VB and I trying use the value of an Element DBName to find the the active SQL database name to connect to. I have looked over a lot of code but it has just made more confused. Any help would be great!
Below is the code for the sub I am trying to use the variable in. I am trying to get the DBName from an xml document. The structure of the xml is as follows
<db>
<User>DBUser2</User>
<Password><![CDATA[xka2bOHaQZWesxHLFHlWaVw7JscbNFCobXbqYWc5rwppoNkAn3K1uqriSCHdEzyY/FNDdbgRJTzDEIM8Jc5PYTBzfMUC5UIDtr16a64Xj7MRGI4/AvRcys/fIQDZQ947GesAc1rF/kbZu8AaZDVTjwObbNPT2L/h+IA6WjM9lqv6BOCi4dUeKxx5AneCBy2TJdifxEPdAIOT9lqTm5/aHFD0JgqSn0OTtWbLuYX9KX9uvA8L8zEH51yEmGl258aRVfpGfyxph/cpdnW1miRk4Q==]]></Password>
<Server>N127.0.0.1\CESSQL</Server>
<ServerDatabase>Marino</ServerDatabase>
<BackupServer></BackupServer>
<BackupDatabase></BackupDatabase>
<MasterPassword><![CDATA[EFmUxlkmQfIx4w18oQZ1dtCxAIXIyBZPCelL8csYX3E5NuHBZNI42UXNhFxmu87Ksj5CbQpC1WNTj4jnLaaq7nX6Oa4z3M7glLAeRaXWGAd3VqWfADRQAW3RCKKSJRMK3jwRWHJjY1Vp2hgn9CuMACvYHZUrUyK6nJ9HMiwaXcUJKtm4vl0toQNpwIuGvT2cfMJgvpjXJhTBfxKE75ZWeAldXhX5h/c6LYMQ6DE79uuhdbisfmIrXTskKTcceiRjWU2jTFumpjhM1tUqEoBFLw==]]></MasterPassword>
Imports System.Data
Imports System.IO
Imports System.Xml
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
m_xmld = New XmlDocument()
m_xmld.Load("C:\FPOS5\Data\dbinfo.xml")
m_nodelist = m_xmld.SelectNodes("/DB/ServerDatabase")
For Each m_node In m_nodelist
Dim ServerDatabaseValue = m_node.Attributes.GetNamedItem("ServerDatabase").Value
Console.Write(ServerDatabaseValue)
Next
Dim con As New SqlClient.SqlConnection("server=127.0.0.1\CESSQL;database=" & DBName & ";User ID=;Password=")
Dim cmd As New SqlClient.SqlCommand
Dim DriverNumber2 As Integer
Dim CheckNumber2 As Integer
DriverNumber2 = TextBox1.Text
CheckNumber2 = TextBox2.Text
Try
con.Open()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
cmd = New SqlClient.SqlCommand("Update Sale Set DriverID =" & DriverNumber2 & "where CheckNumber =" & CheckNumber2 & "")
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Done")
End Sub
If your question is about how to read from an XML file, here is an example.
Assuming this is declared:
Dim xml = <db>
<User>DBUser2</User>
<Password><![CDATA[xka2bOHaQZWesxHLFHlWaVw7JscbNFCobXbqYWc5rwppoNkAn3K1uqriSCHdEzyY/FNDdbgRJTzDEIM8Jc5PYTBzfMUC5UIDtr16a64Xj7MRGI4/AvRcys/fIQDZQ947GesAc1rF/kbZu8AaZDVTjwObbNPT2L/h+IA6WjM9lqv6BOCi4dUeKxx5AneCBy2TJdifxEPdAIOT9lqTm5/aHFD0JgqSn0OTtWbLuYX9KX9uvA8L8zEH51yEmGl258aRVfpGfyxph/cpdnW1miRk4Q==]]></Password>
<Server>N127.0.0.1\CESSQL</Server>
<ServerDatabase>Marino</ServerDatabase>
<BackupServer></BackupServer>
<BackupDatabase></BackupDatabase>
<MasterPassword><![CDATA[EFmUxlkmQfIx4w18oQZ1dtCxAIXIyBZPCelL8csYX3E5NuHBZNI42UXNhFxmu87Ksj5CbQpC1WNTj4jnLaaq7nX6Oa4z3M7glLAeRaXWGAd3VqWfADRQAW3RCKKSJRMK3jwRWHJjY1Vp2hgn9CuMACvYHZUrUyK6nJ9HMiwaXcUJKtm4vl0toQNpwIuGvT2cfMJgvpjXJhTBfxKE75ZWeAldXhX5h/c6LYMQ6DE79uuhdbisfmIrXTskKTcceiRjWU2jTFumpjhM1tUqEoBFLw==]]></MasterPassword>
</db>
It's just one line of code:
xml.Element("ServerDatabase").Value
Or, to keep your variable names:
Dim ServerDatabaseValue As String = xml.Element("ServerDatabase").Value
Always specify variable types. To help you with that, you can set Option Strict On and Option Infer Off in your project settings. This can improve your code quality by forcing you into certain (good) development habits.
I don't exactly sure what you want but you will need to parse the XML and use the XML nodes/element in your connection string. I am not sure even it is a good idea, see this link for parsing XML in VB it is easy.http://www.codeproject.com/Articles/4826/XML-File-Parsing-in-VB-NET

Inserting variables into a query string - it won't work!

Basically i have a query string that when i hardcode in the catalogue value its fine. when I try adding it via a variable it just doesn't pick it up.
This works:
Dim WaspConnection As New SqlConnection("Data Source=JURA;Initial Catalog=WaspTrackAsset_NROI;User id=" & ConfigurationManager.AppSettings("WASPDBUserName") & ";Password='" & ConfigurationManager.AppSettings("WASPDBPassword").ToString & "';")
This doesn't:
Public Sub GetWASPAcr()
connection.Open()
Dim dt As New DataTable()
Dim username As String = HttpContext.Current.User.Identity.Name
Dim sqlCmd As New SqlCommand("SELECT WASPDatabase FROM dbo.aspnet_Users WHERE UserName = '" & username & "'", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(i)("WASPDatabase") Is DBNull.Value Then
WASP = ""
Else
WASP = "WaspTrackAsset_" + dt.Rows(i)("WASPDatabase")
End If
Next
End If
connection.Close()
End Sub
Dim WaspConnection As New SqlConnection("Data Source=JURA;Initial Catalog=" & WASP & ";User id=" & ConfigurationManager.AppSettings("WASPDBUserName") & ";Password='" & ConfigurationManager.AppSettings("WASPDBPassword").ToString & "';")
When I debug the catalog is empty in the query string but the WASP variable holds the value "WaspTrackAsset_NROI"
Any idea's why?
Cheers,
jonesy
alt text http://www.freeimagehosting.net/uploads/ba8edc26a1.png
I can see a few problems.
You are using concatenation in a SQL statement. This is a bad practice. Use a parameterized query instead.
You are surrounding the password with single quotes. They are not needed and in fact, I'm surprised it even works assuming the password itself does not have single quotes.
You should surround classes that implement IDisposable with a Using block
You should recreate the WASP connection object in GetWASPcr like so:
Public Sub GetWASPAcr()
Dim username As String = HttpContext.Current.User.Identity.Name
Dim listOfDatabaseConnectionString As String = "..."
Using listOfDatabaseConnection As SqlConnection( listOfDatabaseConnectionString )
Using cmd As New SqlCommand("SELECT WASPDatabase FROM dbo.aspnet_Users WHERE UserName = #Username")
cmd.Parameters.AddWithValue( "#Username", username )
Dim dt As New DataTable()
Using da As New SqlDataAdapter( cmd )
da.Fill( dt )
If dt.Rows.Count = 0 Then
WaspConnection = Null
Else
Dim connString As String = String.Format("Data Source=JURA;Initial Catalog={0};User Id={1};Password={2};" _
, dt.Rows(0)("WASPDatabase") _
, ConfigurationManager.AppSettings("WASPDBUserName") _
, ConfigurationManager.AppSettings("WASPDBPassword"))
WaspConnection = New SqlConnection(connString);
End If
End Using
End Using
End Using
End Sub
In this example, listOfDatabaseConnectionString is the initial connection string to the central database where it can find the catalog name that should be used for subsequent connections.
All that said, why would you need a class level variable to hold a connection? You should make all your database calls open a connection, do a sql statement, close the connection. So, five database calls would open and close a connection five times. This sounds expensive except that .NET gives you connection pooling so when you finish with a connection and another is requested to be opened, it will pull it from the pool.
Your string passed into the constructor for this SqlConnection object will be evaluated when the class is instantiated. Your WASP variable (I'm assuming) won't be set until the method you have shown is called.
Might want to quit looking one you have found your database:
For i As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(i)("WASPDatabase") Is DBNull.Value Then
WASP = ""
Else
WASP = "WaspTrackAsset_" + dt.Rows(i)("WASPDatabase")
break
End If
Next
[link text][1]You are building your string on the fly by adding the value of a column to a string. So, for the row in question for the column "WASPDatabase" was tacked on to your string. So you got what it had. On another note, your earlier query of "select ... from ... where ..." where you are manually concatinating the string of a variable makes you WIDE OPEN to SQL-Injection attacks.
Although this link [1]: how to update a table using oledb parameters? "Sample query using parameterization" is to a C# sample of querying with parameterized values, the similar principles apply to most all SQL databases.
At the time you're creating the new connection, WASP is holding the value you want it to be holding? It is a string data type? Try adding .ToString after WASP and see if that helps anything.
Interesting problem. =-)
The problem is, as Paddy already points out, that the WaspConnection object gets initialized before you even have the chance to call GetWASPAcr. Try this:
Public Sub GetWASPAcr()
'[...]
End Sub
Dim _waspConnection As SqlConnection
Public Readonly Property WaspConnection As SqlConnection
Get
If _waspConnection Is Nothing Then
GetWASPAcr()
_waspConnection = New SqlConnection("Data Source=JURA;Initial Catalog=" & WASP & ";User id=" & ConfigurationManager.AppSettings("WASPDBUserName") & ";Password='" & ConfigurationManager.AppSettings("WASPDBPassword").ToString & "';")
End If
Return _waspConnection
End Get
End Property