SQL query returning 'Overload resolution error' - sql

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

Related

VB.net insert into error [duplicate]

This question already has an answer here:
Syntax error in INSERT INTO Statement when writing to Access
(1 answer)
Closed 7 years ago.
I'm using Microsoft Visual Studio 2013 and im trying to make a registration form for my account database using VB.NET. This is my code so far:
Private Sub btnRegistery_Click(sender As Object, e As EventArgs) Handles btnRegistery.Click
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(usernme , passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.ExecuteNonQuery()
End Sub
The code compiles fine, but when i try to register any new information i get the following message:
A first chance exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
What could be a solution and cause for this problem?
Your query seems wrong: ... VALUES(usernme, passwrd)... --
Here the usernmeand passwrd are not variables for database, but just plain text in the query.
Use parameters, like this:
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String = "INSERT INTO [tbl_user] ([username], [password]) VALUES (#usernme, #passwrd)"
Using cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
End using
End using
You aren't including the actual variable information missing the quotations, like
VALUES ('" & usernme & '", ...etc
You should be using parameters to avoid errors and sql injection:
sqlQry = "INSERT INTO tbl_user (username, password) VALUES(#usernme, #passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
Dim cnn As New OleDb.OleDbConnection
Private Sub RefreshData()
If Not cnn.State = ConnectionState.Open Then
'-------------open connection-----------
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select stdID as [StdIdTxt]," &
"Fname as [FnameTxt] ,Lname,BDy,age,gender,address,email,LNO,MNO,course" &
"from studentTB order by stdID", cnn)
Dim dt As New DataTable
'------------fill data to data table------------
da.Fill(dt)
'close connection
cnn.Close()
End Sub
Private Sub AddNewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewBtn.Click
Dim cmd As New OleDb.OleDbCommand
'--------------open connection if not yet open---------------
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
'----------------add data to student table------------------
cmd.CommandText = "insert into studentTB (stdID,Fname,Lname,BDy,age,gender,address,email,LNO,MNO,course)" &
"values (" & Me.StdIdTxt.Text & "','" & Me.FnameTxt.Text & "','" & Me.LNameTxt.Text & "','" &
Me.BdyTxt.Text & "','" & Me.AgeTxt.Text & "','" & Me.GenderTxt.Text & "','" &
Me.AddTxt.Text & "','" & Me.EmailTxt.Text & "','" & Me.Hometxt.Text & "','" & Me.mobileTxt.Text & "','" & Me.Coursetxt.Text & "')"
cmd.ExecuteNonQuery()
'---------refresh data in list----------------
'RefreshData()
'-------------close connection---------------------
cnn.Close()
This insert error is nothing but a syntax error, there is no need for changing your code. please avoid reserved words like "password" form your database. This error is due to the field name password
The SQL string should look like this
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(" & usernme & "', " & passwrd & ")"
The values usernme & passwrd aren't valid to the database.
Beyond that you really should look into using a Command object and parameters.

connection String works when declared but not in variable VB.NET

Connection works but not if I set it with button:
Public Class Form1
Private Cnstring As String
Private connection As New SqlConnection("Server=server; Database=databaseName; User Id=user; Password=password")
using the following for variable in the button_click
Cnstring = "Server=" & Server.Text & "; Database=" & Database.Text & "; User Id=" & UserID.Text & "; Password=" & Password.Text & ";"
connection.ConnectionString = Cnstring
Not sure what I'm doing wrong
MessageBox.Show(Cnstring)
Shows the same connectionstring as the original declaration

.NET access error INSERT INTO

I am trying to insert textbox text into a database using VISUAL STUDIO here is my code:
Dim usernme, passwrd As String
usernme = REG_USER_USERNAME.Text
passwrd = REG_USER_PASSWORD.Text
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Login.accdb"
myConnection.Open()
Dim sqlQry As String = "INSERT INTO Admins (USERNAME, PASSWORD) VALUES('" & usernme & "','" & passwrd & "')"
MsgBox(sqlQry)
Dim cmd As OleDbCommand = New OleDbCommand(sqlQry, myConnection)
cmd.ExecuteNonQuery()
myConnection.Close()
But i get an exception error including this:
Additional information: Syntax error in INSERT INTO statement.
Whats wrong with my code, i have quotation marks round the values too!
The direct answer is that Password is a reserved word in Access. Thus:
Dim sqlQry As String = "INSERT INTO Admins (USERNAME, [PASSWORD]) VALUES('" & usernme & "','" & passwrd & "')"
That said, as you do a direct concatenation with non-sanitised user input, do follow the advices posted by #Plutonix.
You could try it this way.
*Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
' Requires: Imports System.Data.OleDb
' ensures the connection is closed and disposed
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=""C:\your_path_here\InsertInto.mdb"";" & _
"Persist Security Info=False")
' open connection
connection.Open()
' Create command
Dim insertCommand As New OleDbCommand( _
"INSERT INTO Table1([inputOne] , [inputTwo] , [inputThree]) " & _
"VALUES (#inputOne, #inputTwo, #inputThree);", _
connection)
' Add the parameters with value
insertCommand.Parameters.AddWithValue("#inputOne", TextBox1.Text)
insertCommand.Parameters.AddWithValue("#inputTwo", TextBox2.Text)
insertCommand.Parameters.AddWithValue("#inputThree", TextBox3.Text)
' you should always use parameterized queries to avoid SQL Injection
' execute the command
insertCommand.ExecuteNonQuery()
MessageBox.Show("Insert is done!!")
End Using
End Sub
End Class*

Drop a SQL Server login using 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")

VB.Net SQL insert difficulty

i'm programing in vs 2010 a vb.net project.
don't know what is happening when i insert the data because it gives this message:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
what's wrong?
here is the part of the code that makes it
Imports System.Data
Imports System.Data.SqlClient
Public Class atl
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim myConnectionString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\uss.mdf;Integrated Security=True;User Instance=True"
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click
myconnection = New SqlConnection(myConnectionString)
mycommand = New SqlCommand("insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) values ('" & txtNome.Text & "','" & txtMorada.Text & _
"','" & ComboSexo.Text & "','" & CType(txtDataN.Text, DateTime).ToString("yyy-MM-dd") & "','" & txtTelemovel.Text & "','" & ComboBox1.Text & "')", myconnection)
myconnection.Open()
Try
mycommand.ExecuteNonQuery()
Label1.Content = "O atleta " + txtNome.Text + " foi registado!!!"
Catch ex As Exception
Label1.Content = "Falhou a ligação a base de dados!!!"
End Try
End Sub
does some of your values contains single quote? your statement is vulnerable with sql injecton. why don't you use sql parameters?
Dim myConnectionString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\uss.mdf;Integrated Security=True;User Instance=True"
Dim sqlStatement = "insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) "
sqlStatement &= "VALUES (#nome, #morada, #sexo, #datan, #telf, #desporto)"
Using xConn As New SqlConnection(myConnectionString)
Try
Dim xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("#nome", txtNome.Text)
.Parameters.AddWithValue("#morada", txtMorada.Text)
.Parameters.AddWithValue("#sexo", ComboSexo.Text)
.Parameters.AddWithValue("#datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd") )
.Parameters.AddWithValue("#telf", txtTelemovel.Text)
.Parameters.AddWithValue("#desporto", ComboBox1.Text)
End With
xConn.Open()
xComm.ExecuteNonQuery()
xComm.Dispose()
Catch ex As SqlException
MsgBox (ex.Message)
End Try
End Using
also you have a mistake here: CType(txtDataN.Text, DateTime).ToString("yyy-MM-dd") it should yyyy-MM-dd not yyy-MM-dd