How to query an ACCESS database to a variable - sql

I am trying to query an access database to find in a row exists in the database and if the value of IsManager = True or not. I'm new to using databases so any help is good thanks yall :) <3
Try
Dim SQL As String
Dim CMD As New OleDb.OleDbCommand
Dim DT As New DataTable
Dim D_A As New OleDb.OleDbDataAdapter
MainMenu.Con.Open()
SQL = ("SELECT * FROM Staff WHERE Login = " & ID)
CMD.Connection = MainMenu.Con
CMD.CommandText = SQL
D_A.SelectCommand = CMD
D_A.Fill(DT)
Catch ex As Exception
MsgBox(ex.Message)
Finally
MainMenu.Con.Close()
End Try

Don't fill a DataTable and then retrieve a field inside it.
Insert in a variable the value you want to get.
Dim IsManager as Boolean
Try
Dim SQL As String
Dim CMD As New OleDb.OleDbCommand
Dim D_A As New OleDb.OleDbDataAdapter
SQL = ("SELECT IsManager FROM Staff WHERE Login = " & ID)
CMD.Connection = MainMenu.Con
CMD.CommandText = SQL
D_A.SelectCommand = CMD
MainMenu.Con.Open()
Dim Dr as OleDbDataReader = CMD.ExecuteReader
Dr.Read()
IsManager = Dr.Item("IsManager")
Dr.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MainMenu.Con.Close()
End Try

Related

No results to select sum to another table with OLEDB in VB.NET

Dear All Master,
I have tried but there is no result from sql select sum and only appears group from the column "PNM". Is there anything wrong with the sql I created?. is there any other solution?.
I don't know why it doesn't appear in the sum value in the "BLC" column in the TEMPTABL table.
Thanks
Private Sub fillDataGridView1()
Try
Dim query As String = "SELECT PNM,NOD,QTY,CIU,DPR FROM GSDTS WHERE QTY > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using da As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
da.Dispose()
source1.DataSource = dt
Me.DataGridView1.DataSource = source1
Me.DataGridView1.Refresh()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Private Sub fillDataGridView2()
Try
Dim query As String = "select * FROM TEMPTABL"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using da As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
da.Dispose()
source2.DataSource = dt
Me.DataGridView2.DataSource = source2
Me.DataGridView2.Refresh()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Sub deltemptabl()
Try
Dim sql As String = "DROP TABLE TEMPTABL"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch myerror As Exception
MessageBox.Show("Error: " & myerror.Message)
End Try
End Sub
Sub temptablsum()
Try
'here is the line of code below sql select sum
Dim sql As String = "select PNM, sum((qty*ciu)*(1-dpr/100)) AS BLC INTO TEMPTABL from GSDTS group by PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch myerror As Exception
MessageBox.Show("Error: " & myerror.Message)
End Try
End Sub
DPR is null, therefore it will return null when you try to compute it. You can account for that with isnull(), setting it to 1 (or whatever fits the scenario) whenever the column could be null
sum((qty*ciu)*(1-ISNULL(dpr,1)/100))
Edit:
After looking over it again, you may want to apply the isnull function to the entire sum to return 0 if null. It's difficult to give exacts as I dont know what each column means or specifics to the scenario
ISNULL(sum((qty*ciu)*(1-dpr/100)),0)
Edit/option 2:
Encapsulate that column in a case statement to handle the scenario if needed.
CASE WHEN DPR IS NOT NULL THEN sum((qty*ciu)*(1-dpr/100)) ELSE ReturnSomethingElse END AS DPR
Option 3:
Change the table column and front end to not accept null values if it's not viable for the scenario

How to count number of rows in a sql table with vb.net using sqlclient class

SELECT count(*) FROM table name
this above code work fine in standalone sql table, but who can I do this simple task with in vb.net wpf project ?
This is only a sample ..just check and try your own way.
Sample:
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;
User ID=UserName;Password=Password"
sql = "Select count(*) from table"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
MsgBox("Count =" & sqlReader.Item(0))
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
If your query return more than one values you can use SqlDataReader(), but if you are sure your query will return only a single value you can use ExecuteScalar() and if your query wont return any result, eg:- insert.it will insert value not return any data so we can use ExecuteNonQuery().The ExecuteNonQuery() will return a result which indicate is it successful or failure. If you want you can assign the same else no need.
Use SqlCommand.ExecuteScalar() method to execute query that return singular/scalar value (example based on that link) :
Dim count As Integer
Dim connString = "connection string to your database here"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM MyTable", conn)
Try
conn.Open()
count = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using

How to display total sum from database to textboxes?

Guys How can I display the sum from database to textbox1 and textbox2?
Private Sub totalquiz()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
sSQL = "Select sum(quiz) as score,sum(total) as total FROM prelimquiz where [username]='ad' And studentID='1111111'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
textbox1.Text =dt.Rows[2].ToString()
textbox2.text =dt.rows[3].ToString()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I dont know how to correctly get the total sum and display to textboxes.
your query will return only one record containing the sum you wanted
to access it simply do the following
dt.Rows[0]["score"].ToString();
dt.Rows[0]["total"].ToString();
hope it will help you
regards

I get only column headers using sqldatareader and datagridview

I have a SQL Server 2008 express with a database and a table and using VB 2010 express.
I am trying to read from that table with sqldatareader, but I only one row in the datagridview with the column headers, no row with data.
What am I doing wrong? (I'm a newbe).
The connection string is :
Data Source=xxxxxxxxxx\SQLEXPRESS;Initial Catalog=Masteca_Inventory;Integrated Security=True
Dim searchStr As String = ""
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlStr As String
Public bindingSource1 As New BindingSource()
connetionString = My.Settings.SQLconnSTR
sqlStr = "SELECT * FROM Piese WHERE " & searchStr 'searchStr is OK I fill it elsewhere
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sqlStr, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
Using sqlReader
Dim dTable As New DataTable
dTable.Load(sqlReader)
bindingSource1.DataSource = dTable
End Using
SearchReport.DataGridView1.DataSource = bindingSource1
'SearchReport is another form
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
SearchReport.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
You are not reading the data as a group (you are fetching only one result).
You will need to adjust the code to use a While sqlReader.Read;
Example;
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
Try
'Do the work needed
rowResult += sqlReader(0) 'This will contain the result script
Catch ex As Exception
'Catch exception
End Try
End While
Something like that should work (I have not tested the code but the concept is the same).
PS - I strongly suggest you adjust your script to add a Where clause and / or the columns needed (Select * is not a "good practice")
Hope this helps.

VB | Loading SQL Query into Combobox

I am trying to fill a combobox with a SQL Result
I think my problem is handling the data in the datatable form.
Dim sql As String
Dim sqlquery As String
Dim ConnectionString As String
ConnectionString = "Data Source=(local);Initial Catalog=Control;Persist Security Info=True;User ID=user;Password=pass"
sqlquery = "Select dbName from Databases"
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using conn As SqlCommand = New SqlCommand(sqlquery, conn)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(cmboxDatabaseName)
End Using 'comm
End Using 'conn
When I run the program I just stare at a sad empty combobox.
Almost right, but you need to Load the datatable using the DataReader.
Then assing the DataTable to the DataSource of the Combo
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
' as an example set the ValueMember and DisplayMember'
' to two columns of the returned table'
cmboxDatabaseName.ValueMember = "IDCustomer"
cmboxDatabaseName.DisplayMember = "Name"
cmboxDatabaseName.DataSource = dt
End Using 'comm
End Using 'conn
Also you could set the combobox ValueMember property to the name of the column that you will use as key for future processing and the DisplayMember property to the column name that you want to display as text to choose from for your user
you can also do it as
Dim Con = New SqlConnection(_ConnectionString)
Dim cmdAs New SqlCommand
Dim dr As New SqlDataReader
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.