Hello guys i have simple Question about what is the difference between these SQlConnection Strings
1.
Dim Con As New SqlConnection("Server = Z\SQL; Database = Project; id = zzz; pwd = zzz integrated Security = true")
Dim Con As New SqlConnection("Driver = {SQL SERVER}; Server = Z\SQL; Database = Project; id = zzz; pwd = zzz integrated Security = true")
Dim Con As New SqlConnection("#Server = Z\SQL; Database = Project; id = zzz; pwd = zzz integrated Security = true")
Also Which is the most optimal procedure?
Thanks before
the 1 and 2 Code are the same, and if you don't want to access your SQL by Windows Aunthetication then set the Integrated Security to False and then add UID (Sql Login Id) & PWD (Password) into the string.
thanks anyone.
Related
I am using below code to query Active Directory and get list of users. The code is working in VB Macro. I modified a bit syntactically to make it work on VB.NET (VS 2022).
The RecordCount is appearing as 900 but I am not able to bind it to DataGridView. Not enough knowledge of VB. I referred to samples which use OleDB DataAdapter but in the code below the command object is different so it throws error.
Also, this line throws error. It is working in Excel Macro.
oCommand1.Properties("SearchScope") = 2
Please advise how to display records in Grid:
'Open the connection.
'This is the ADSI OLE-DB provider name
oConnection1.Provider = "ADsDSOObject"
oConnection1.Open("Active Directory Provider")
oCommand1.ActiveConnection = oConnection1
strQuery = "select c, l, SAMAccountName,displayName, distinguishedName, cn, sn,givenName,title,mail, department, manager, userAccountControl " &
" from 'GC://dc=TestAD,dc=net'" &
"WHERE objectCategory='Person'" &
"AND objectClass='user'"
oCommand1.CommandText = strQuery
oCommand1.Properties("SearchScope") = 2
rs = oCommand1.Execute()
lblRecords.Text = rs.RecordCount
DataGridView1.DataSource = rs
oConnection1.Close()
Use Directory services and LDAP query :
Imports System.DirectoryServices
{......}
Dim oD As DirectoryEntry
Dim oS As DirectorySearcher
oD = New DirectoryEntry("LDAP://RootDSE")
oS = New DirectorySearcher(oD)
oS.Filter = "(&(objectClass=user))"
oS.SearchScope = SearchScope.Subtree
''''''''''''''''''''''
'by default all objects property will be retrieve
'if you just need somme of them use
'oS.PropertiesToLoad.Add("SAMAccountName")
'oS.PropertiesToLoad.Add("displayName")
'oS.PropertiesToLoad.Add("CN")
'etc...
'that will speed up search
''''''''''''''''''''''
Dim src As SearchResultCollection = oS.FindAll()
oD.Close()
oS.Dispose()
Dim dt As New DataTable()
dt.Columns.Add("samaccountname")
dt.Columns.Add("givenName")
dt.Columns.Add("sn")
dt.Columns.Add("mail")
' add here others columns needed in dt
For Each sr As SearchResult In src
Dim dr As DataRow = dt.NewRow()
Dim de As DirectoryEntry = sr.GetDirectoryEntry()
dr("samaccountname") = de.Properties("samaccountname").Value.ToString()
dr("givenName") = de.Properties("givenName").Value.ToString()
dr("sn") = de.Properties("sn").Value.ToString()
dr("mail") = de.Properties("mail").Value.ToString()
'etc... fill others dt columns based on propertys needed
dt.Rows.Add(dr)
de.Close()
Next sr
lblRecords.Text = dt.rows.count-1
DataGridView1.DataSource = dt
how do I put an int variable in sql?
int x = Convert.ToInt32(Session["id"]);
string MySQL = #"UPDATE users SET
email = '"+Request.Form["email"]+"', pname =
'"+Request.Form["pname"]+"', accountname=
'"+Request.Form["accountname"]+"', pid = '"+Request.Form["pid"]+"', age =
'"+Request.Form["age"]+"',passw = '"+Request.Form["passw"]+"' where
id='x';";
Please don't use concatenated values in your SQL command. You are exposing your application to SQL Injection Attacks. Read more here.
Use SqlParameters instead. It is the proper way to do and safer when you are running sql commands against your database from your application.
If a value is int covert it to integer:
command.Parameters.AddWithValue("#id", int.Parse(Request.Form["id"]));
Here is a example of how to use parameters.
string mySql = #"UPDATE users SET email = #email, pname = #pname, accountname = #accountname, pid = #pid, age = #age, passw = #passw where id = #id;";
string connectionString = "Server=localhost\\SQLEXPRESS;Database=[your database];User Id=sa;Password=[your password];";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(mySql, connection);
command.Parameters.AddWithValue("#email", Request.Form["email"]);
command.Parameters.AddWithValue("#pname", Request.Form["pname"]);
command.Parameters.AddWithValue("#accountname", Request.Form["accountname"]);
command.Parameters.AddWithValue("#pid", Request.Form["pid"]);
command.Parameters.AddWithValue("#age", int.Parse(Request.Form["age"]));
command.Parameters.AddWithValue("#passw", Request.Form["passw"]);
command.Parameters.AddWithValue("#id", int.Parse(Request.Form["id"]));
connection.Open();
command.ExecuteNonQuery();
}
More about SqlCommand here.
I'm trying to rewrite my code to prevent vulnerability to SQL Injection. I see code for inserting or updating tables, but not for just getting a value. Here is the code I have that is vulnerable:
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
cmde.CommandText = "SELECT EmployeeID FROM tblEmployees where login = '" & vname & "'"
cmde.CommandType = CommandType.Text
cmde.Connection = sqlConnection
sqlConnection.Open()
'employeeid
rve = cmde.ExecuteScalar()
sqlConnection.Close()
I started rewriting the code and this is what I have so far:
sql1 = "Select EmployeeID from tblEmployees where login = #loginname"
cmde = new sqlcommand(sql1)
This is where I'm stuck:
cmde.parameters.????("#loginname", vname)
cmde.ExecuteReader()
I'm not adding or updating or inserting - I just want the value to appear on my webpage. What is the code for this? And is the rest of the code correct? Thanks in advance!
****Continued...
After help, I came up with this code but I'm getting an error - ExecuteReader: Connection property has not been initialized. I'm confused. Here's the code:
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
Dim sqlConnection As New SqlConnection("Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI")
Dim sqlemp As String
Dim cmde As New SqlCommand
Dim rve As Object
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
sqlConnection.Open()
sqlemp = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
cmde = New SqlCommand(sqlemp)
cmde.Parameters.AddWithValue("#loginname", vname)
rve = cmde.ExecuteReader()
sqlConnection.Close()
when I run the code, I have an error message that says: Object reference not set to an instance of an object. I would like to create a code that verify credentials that are in the database. If the user that not enter valid information, an error message appears. Here is my code:
'Declare variables
Dim pwd, username As String
Dim dbpwd, dbUsername As String
'Get credentials variables
username = Me.username.Text
pwd = Me.TextBox2.Text
Dim objConn As MySqlConnection
Dim objDataset As New DataSet
Dim objDataAdapter As MySqlDataAdapter
Dim sqlConn As String
If username <> "" And pwd <> "" Then
objConn = New MySqlConnection("server=localhost;userid=root;password= ;database=mayombe_mdcs")
objConn.Open()
sqlConn = "select agent_id, Password from password where agent_id = " & username & ""
Try
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.Fill(objDataset)
' intRowNumber = sqlR
dbUsername = objDataset.Tables("password").Rows(1).Item(2)
' dbpwd = objDataset.Tables("password").Rows(1).Item(1)
'WriteLine (dbUsername )
'Force users to enter credentiasl
objConn.Close()
'Force user to enter true credentials
If pwd = dbpwd And username = dbUsername Then
open form
Me.Close()
End If
Catch ex As Exception
strMsg As String
Prompt message that tells the user that credentials entered are not correct.
strMsg = String.Format("One of the following is incorrect: {0}* Username entered {0}* Password entered.", Environment.NewLine)
MessageBox.Show(strMsg, "Warning")
End Try
There are some things wrong in your code.
First, if agent_id is a varchar field you need to use single quotes around the value used in the where clause, but it is better to avoid this problem and use a parameterized query.
Second, if you find something then you should refer to the first row using index 0 and to the second column using index 1. Your code assumes that indexing of an array starts at index 1 but this is not true in the NET world. Arrays always start at index 0.
I would try to rewrite your code as this
objDataset = new Dataset()
sqlConn = "select agent_id, Password from password where agent_id = #usr"
using objConn = New MySqlConnection(....)
objConn.Open()
Try
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.SelectCommand.Parameters.AddWithValue("#usr", username)
objDataAdapter.Fill(objDataset)
if objDataset.Tables(0).Rows.Count > 0 Then
dbUsername = objDataset.Tables(0).Rows(0).Item(1).ToString
End If
End Using
I am trying to connect database.sdf on same director. Using following code but gives me connection error. What I am doing wrong. Please help me.
Dim connstring As String
Dim con As SqlCeConnection
Dim command As SqlCeCommand
connstring = "Persist Security Info = False; Data Source = '.\database.sdf', Password = 'pswrd', File Mode = 'shared read'"
con = New SqlCeConnection
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
I think you're missing some code... or maybe that's the problem, you never bind your SqlCeConnection to connstring
Dim con As SqlCeConnection
Dim command As SqlCeCommand
con = New SqlCeConnection("Persist Security Info=False;Data Source=.\database.sdf;Password=pswrd;File Mode=shared read")
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
You do not need the single quotes (') in the different parts of the connection string, and you should be using a semi-colon (;) to separate the different values.
"Persist Security Info = False; Data Source = .\database.sdf; Password = pswrd; File Mode = shared read;"
Apart from that, you do not appear to be using the connection string in your code. You should be using it to open the connection:
con = New SqlCeConnection(connstring)
Check out Connection Strings for great connection string assitance.
It looks like your line:
connstring = "Persist Security Info = False; Data Source = '.\database.sdf', Password = 'pswrd', File Mode = 'shared read'"
is using both "," and ";" to separate the parameters. Update then all to use ";"