Drop a SQL Server login using VB.NET - vb.net

I can successfully create a SQL Server login using VB.NET, but I am facing issues with dropping the login. There are no syntax errors, but login and user are not getting dropped.
Below is the code that I'm using:
Protected Sub Button_Del_Click(sender As Object, e As System.EventArgs) Handles Button_Del.Click
Dim constrDel As String
Dim SrvDel As String
Dim DbDel As String
Dim LoginDel As String
Dim DeleteSQL As String
SrvDel = DropDownList_Instance.SelectedItem.Text
DbDel = DropDownList_Database.SelectedItem.Text
constrDel = "Data Source=" & SrvDel & ";Initial Catalog=" & DbDel & ";Integrated Security=true"
LoginDel = TextBox_Login.Text
Using Con2 As New SqlConnection(constrDel)
Con2.Open()
Dim com As SqlCommand = New SqlCommand(ChkLogin, Con2)
Dim dr As SqlDataReader = com.ExecuteReader()
DeleteSQL = "Drop Login [" + LoginDel + "] Drop User [" + LoginDel + "] "
dr.Close()
com.ExecuteNonQuery()
Con2.Close()
MsgBox("Login Deleted")

Related

Create table from Excel file

I'm trying to create a temp table on my database from an Excel file uploaded by the user. I cannot understand where is the problem and why Visual Studio is throwing that exception.
Code
Private Sub Excel_Load(ByVal filePath As String)
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim sqlCmd As String
Dim filename As String = Path.GetFileNameWithoutExtension(filePath)
'Setting up Connection'
myConn = New SqlConnection("Server=*****;Database=*****;User ID=*****;Password=*****;Integrated Security=SSPI;")
myConn.Open()
'Create table'
sqlCmd = "CREATE TABLE XlsTemp AS (SELECT * FROM EXCELLINK [" & filename & "$])"
'Execute Query'
myCmd = myConn.CreateCommand()
myCmd.CommandText = sqlCmd
myCmd.ExecuteNonQuery()
myConn.Close()
End Sub
Exception
SqlException: The object name 'EXCELLINK' is not valid.
Peu_UNRAE is my Excel file.
At the end I come up with this solution:
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim fileExcelType As String
//Get the file extension in order to use the propper provider
If IO.Path.GetExtension(fileExcel.ToUpper) = ".XLS" Then
fileExcelType = "Excel 8.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
Else
fileExcelType = "Excel 12.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
End If
//Opening excel connection
MyConnection.Open()
Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
MyCommand.TableMappings.Add("Table", " ")
MyCommand.Fill(dt)
//Closing connection
MyConnection.Close()
Remarks:
I used // for the comments because the standar ' was giving some problem here on StackOverflow

SQL query returning 'Overload resolution error'

I have a readini file to connect to my SQL Server table, and in my query code to display data from it, I'm getting an error that I've not been able to solve, is there anybody here who can?
This is the error:
Error 1
Overload resolution failed because no accessible 'New' can be called with these arguments:
'Public Sub New(selectCommandText As String, selectConnection As System.Data.OleDb.OleDbConnection)': Value of type 'SQLServerApplication.readini' cannot be converted to 'System.Data.OleDb.OleDbConnection'.
'Public Sub New(selectCommandText As String, selectConnectionString As String)': Value of type 'SQLServerApplication.readini' cannot be converted to 'String'.
This is the code:
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class frmViewDtb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As readini = New readini()
connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
End Sub
End Class
The line that the error is occurring on is line 13:
Dim da As New OleDbDataAdapter(sql, connection)
Code for getConnectionString;
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
End Function
Thanks in advance if you can get it!
I believe you are getting the error as the constructor for OleDbDataAdpater is expecting two strings and your connection variable isn't a string. I suspect your code needs to look like this:
Dim connection As readini = New readini()
Dim ConnString = connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, ConnString)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
The getConnectionString method also needed amending to add the Return statement:
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
Return s
End Function

Best way to deal with Open Datareader Error (vb.net and mysql)

My Project running on VS 2013 & MySQL, I have declared public variable conn as mysqlconnection and I use the same connection all over the project to perform any database operation.
Public conn As New MySqlConnection
Public Sub createConnection()
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = parseConfigXML()
conn.Open()
End If
End Sub
Public Function parseConfigXML()
Try
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
m_xmld = New XmlDocument()
m_xmld.Load("../../../appconfig.xml")
m_nodelist = m_xmld.SelectNodes("/app/config")
Dim hostname, dbname, dbuser, dbpassword As String
hostname = ""
dbname = ""
dbuser = ""
dbpassword = ""
For Each m_node In m_nodelist
hostname = m_node.ChildNodes.Item(0).InnerText.ToString
dbname = m_node.ChildNodes.Item(1).InnerText.ToString
dbuser = m_node.ChildNodes.Item(2).InnerText.ToString
dbpassword = m_node.ChildNodes.Item(3).InnerText.ToString
Next
Dim connectionString = "Database=" & dbname & "; Data Source=" & hostname & "; User Id=" & dbuser & ";Password=" & dbpassword & "; Character Set=utf8"
Return connectionString
Catch errorVariable As Exception
MsgBox("Oops, An error occured: " & errorVariable.ToString)
End Try
End Function
Whenever connection is required, I use it as follows:
Try
Dim query As String = "select * from tbl_lang where lang_status=1"
Dim cmd As New MySqlCommand(query, conn)
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
Do While dr.Read
cmb.Items.Add(dr.GetString("lang_name"))
Loop
End If
cmb.SelectedItem = "English"
If Not dr.IsClosed Then dr.Close()
Catch ex As Exception
lbl_error.text="Oops, An error occured: " & ex.ToString
End Try
I always have this issue when the code is reused: There is already open datareader for this connection.
What is the best way to deal with it? someone had mentioned to use open new connection for every query and then close it. Somehow, I am not convinced with it as it may create performance issues.
Please suggest the best way to overcome the issue.

Why is Data Not Saved to the Database in my Guestbook Application?

I am creating an application that requires a guestbook.. The data from the database appears on the website however any data I enter from the website doesn't automatically get put into the database.
Here is the code I have..
Protected Sub ButSign_Click(sender As Object, e As EventArgs) Handles ButSign.Click
Dim strDSN As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "
Data source=C:\USERS\SHAUNA WATSON\DESKTOP\PROJECT COPIES\FINAL\APP_DATA\FACTORY.MDF"
Dim strSQL As String = (((("INSERT INTO Guestbook " & "( Name,Address,Email,Comments)" & "VALUES ('")
+ TxtName.Text.ToString() & " ',' ") + TxtAddress.Text.ToString() & " ', '") + TxtEmail.Text.ToString() & " ',' ") + TxtComments.Text.ToString() & " ')"
' set Access connection and select strings
' Create oleDbDataAdapter
Dim myConn As New OleDbConnection(strDSN)
'Create ole Db Command And call ExecuteNonQuery to execute
' a SQL statement
Dim myCmd As New OleDbCommand(strSQL, myConn)
Try
myConn.Open()
myCmd.ExecuteNonQuery()
Catch exp As Exception
Console.WriteLine("Error: {0}", exp.Message)
End Try
myConn.Close()
' open Thans.aspx page after adding entries to the guest book
Response.Redirect("GuestbookThanks.aspx")
End Sub
I'm just wondering if anyone can spot something I may have missed!
You could try changing your code to this:
myConn.Open()
Dim myCmd As New OleDbCommand
With myCmd
.Connection = myConn
.CommandType = CommandType.Text
.CommandText = "INSERT INTO Guestbook (Name,Address,Email,Comments) VALUES (#Name,#Address,#Email,#Comments)"
.Parameters.Add("#Name", OleDbType.VarChar).Value = TxtName.Text
.Parameters.Add("#Address", OleDbType.VarChar).Value = TxtAddress.Text
.Parameters.Add("#Email", OleDbType.VarChar).Value = TxtEmail.Text
.Parameters.Add("#Comments", OleDbType.VarChar).Value = TxtComments.Text
End With
myCmd.ExecuteNonQuery()
myConn.Close()
Don't put this in a Try Block. If you get an error, just post it, and we'll see what the error is.

Check if value exist in DBF database

I am trying to check if value "IAV-1419" exist in second column (ColName) in database named PROMGL.DBF.
I get this error : No value give for one or more required parameters
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV"
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
I am stuck here, if anyone could please check this code for me.
are you sure that your connectionstring is correct????
Data Source=" & FilePath &
how connection string know the database where it point only to "C:\" i think is missing database name
Another personal suggestion make your code more simple to read in example :
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL", con
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
End Using
End Using