is it possible to set a parameter for selecting a table? - sql

sorry for the noob question..but here's what i did
Dim cmd As New SqlCommand("Declare #mychar varchar(60) " & _
"Set #mychar = '" & TextBox2.Text & "'" & _
"Select * from #mychar", conn)
Dim rdr As SqlDataReader = cmd.ExecuteReader
While rdr.Read()
ListView2.Items.Add(rdr("Account"))
End While
rdr.Close()
but i get an error saying "Must declare the table variable "#mychar"." what's wrong ? or is this not just possible ? thanks in advance..

Dim cmd As New SqlCommand(" Select * from " & TextBox2.Text & " ", conn)
Dim rdr As SqlDataReader = cmd.ExecuteReader
While rdr.Read()
ListView2.Items.Add(rdr("Account"))
End While
rdr.Close()

Related

i want to filter my data with this from using visual studio 2015

I want to sort the data in the database with the date as the main condition with 2 date time picker 1 as the starting date and the other as the limit with this code by using between but I do not know the correct query form...my from looks like this the first DTP name is DTPDari and second DTPSampai
Call KONEKSI()
CMD = New OleDbCommand("SELECT * FROM Pembayaran where tanggal_pembayaran BEETWEEN '" & DTPDari.Value & "'AND tanggal_pembayaran = '" & DTPSampai.Value & "'", CONN)
DR = CMD.ExecuteReader
DR.Read()`
From the little what I understand from your question you can use any of the below
(syntax not tested)
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran BETWEEN '" & DTPDari.Value & "' AND '" & DTPSampai.Value & "')
or
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran > '" & DTPDari.Value & "') and (tanggal_pembayaran < '" & DTPSampai.Value & "')
Adding Function sample asper your request
Sub GetDetails()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString.ToString()
Dim connection As New SqlConnection(connectionString)
Dim queryString2 = "SELECT *
FROM dbo.Customers
WHERE (CreationDate BETWEEN #param1 AND #param2)"
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = queryString2
cmd.Connection = connection
cmd.Parameters.AddWithValue("#Param1", from_DateTimePicker.Value.Date)
cmd.Parameters.AddWithValue("#param2", to_DateTimePicker.Value.Date)
connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
'here fill on datatable Or anything you want
End While
connection.Close()
End Sub

VB.Net - ExecuteReader: CommandText property has not been initialized

I know there are some threads about this topic, but for some reason nothing of these things given there didn't work for me. So that is my code:
Dim strAccSQL As String = "SELECT nUserNo FROM dbo.tUser WHERE sUserID='" & AccountID.Text & "';"
Dim catCMDAcc As SqlCommand = New SqlCommand(strAccSQL, AccCon)
Dim myAccountReader As SqlDataReader = catCMDAcc.ExecuteReader()
While myAccountReader.Read
AccountNo.Text = myAccountReader(0)
End While
myAccountReader.Close()
Con.Close()
Con.Open()
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
InfoTextBox.Text &= Environment.NewLine & Now & " Account: " & AccountID.Text & " Found"
CharacterName.Properties.Items.Clear()
While myReader.Read()
CharacterName.Properties.Items.Add(myReader(0))
End While
myReader.Close()
AccCon.Close()
Con.Close()
Anyone got an idea for my problem?
As the errormessage states, your CommandText is empty string here (strSQL2):
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
You cannot execute an empty sql-clause.

SQL Update not updating records in access

Trying to update the values of Comment and ProgressValue inside a table in access. The message box at the end pops up but none of the values are changed.
Sub UpdateWeeklyReport()
Dim con As OleDbConnection
Dim com As OleDbCommand
con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\ProjectDatabase.mdb")
com = New OleDbCommand("Update WeeklyReport Set Comment = #Comment, ProgressValue = #ProgressValue Where [EntryDate]='" & CBDate.SelectedValue.ToString & "' AND [AdminNo]=" & CBAdmin.SelectedValue & " AND [ClassCode]='" & CBClass.SelectedItem.ToString & "'", con)
con.Open()
com.Parameters.Add("#Comment", OleDbType.LongVarChar).Value = txtComment.Text
com.Parameters.Add("#ProgressValue", OleDbType.Integer).Value = CBProgress.Text
com.ExecuteNonQuery()
con.Close()
MessageBox.Show("Report Changed")
intialconnection()
End Sub
End Class

syntax error in FROM clause in vb.net

Dim nm As String
Dim pass As String
nm = TextBox1.Text
pass = TextBox2.Text
Try
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Pavilion\Documents\Visual Studio 2010\Projects\WindowsApplication5\Ent.accdb"
cn.Open()
Dim sql As String
sql = "SELECT * FROM user WHERE UName='" & nm & "'AND Pwd='" & pass & "'"
cmd = New OleDbCommand(sql, cn)
dr = cmd.ExecuteReader
While (dr.Read())
If ((nm.Equals(dr(0))) And pass.Equals(dr(1))) Then
MessageBox.Show("Login Sucessful")
End If
End While
Catch ex As Exception
MsgBox("Login Failed :" & ex.Message)
End Try
This code is giving the following error syntax error in FROM clause
#Tim is correct, but I think you might also have problem with your SQL as user is a reserved word. If I execute
SELECT * FROM user WHERE UName='fred' AND Pwd='123'
in SQL Server
I get told Incorrect syntax near the keyword 'user'.
You can overcome this by putting [] around the tablename, i.e.
Select * FROM [user] WHERE UName='fred' AND Pwd='123'
If the code you posted is copy and paste, you're missing a space between the username and the AND keyword.
Your code:
"SELECT * FROM user WHERE UName='" & nm & "'AND Pwd='" & pass & "'"
Should be:
"SELECT * FROM user WHERE UName='" & nm & "' AND Pwd='" & pass & "'"
However, you should use parameterized queries to avoid the possibility of SQL injection attacks. Something like this:
sql = "SELECT * FROM user WHERE UName=#nm AND Pwd=#pass"
cmd = New OleDbCommand(sql, cn)
cmd.Parameters.AddWithValue("#nm", TextBox1.Text)
cmd.Parameters.AddWithValue("#pass", TextBox2.Text)
cmd.CommandType = CommandType.Text
dr = cmd.ExecuteReader
Try
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Pavilion\Documents\Visual Studio 2010\Projects\WindowsApplication5\Ent.accdb"
cn.Open()
Dim sql As String
sql = "SELECT * FROM user WHERE UName='" + nm + "'AND Pwd='" + pass + "'"
cmd = New OleDbCommand(sql, cn)
dr = cmd.ExecuteReader
While (dr.Read())
If ((nm.Equals(dr(0))) And pass.Equals(dr(1))) Then
MessageBox.Show("Login Sucessful")
End If
End While
Catch ex As Exception
MsgBox("Login Failed :" & ex.Message)
End Try
"SELECT Firstname FROM [RegUser] where Firstname=#d3 and password=#d4"
i just enclose my table name into brackets and its done.. it works actually
i hope this will help you a lot..

Data Reader formatting output

I'm using the following function to generate a list of users connected to a selected database. How would I change this to a single line for multiple identical results?
For example: "sa (3) - MYCOMPUTER" rather than listing "sa - MYCOMPUTER" three times?
Function ConnectedUsers(ByVal SelectedDatabase As String, ByVal SelectedInstance As String)
Dim myCommand As SqlCommand
Dim dr As SqlDataReader
Dim mystring As String = String.Empty
Try
Dim myConn As New SqlConnection(ConnectionString)
myConn.Open()
myCommand = New SqlCommand("select loginame,hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & ";", myConn)
dr = myCommand.ExecuteReader()
While dr.Read()
mystring += GetFullName(dr(0).ToString().Trim()) & " - " & dr(1).Trim() & vbCrLf
End While
dr.Close()
myConn.Close()
Catch e As Exception
MessageBox.Show(e.Message)
End Try
Return mystring
End Function
Thanks.
The SQL Command should be
select loginame, count(*) as Nbr, hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & "' group by loginame;"
and you should change the display to show the count (Nbr in this example) to be something like:
mystring += GetFullName(dr(0).ToString().Trim()) & "(" & dr(1).Trim() & ") - " & dr(2).Trim() & vbCrLf