How to check if table is empty in VB.net [duplicate] - sql

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Checking for an SQL result in VB.NET
I have login form which is redirect user for their levels but before to that if there is no any user on the data table I would like to redirect to create admin form. I have all the forms but I didn't manage to redirect them because I don't know how to create statement. Could you please help me about solution.
Dim con As SqlCeConnection
Dim command As SqlCeCommand
con = New SqlCeConnection("Persist Security Info=False;Data Source=.\database.sdf;Password=********;File Mode=shared read")
con.Open()
command = New SqlCeCommand("select * from users where Name=? and Password=?", con)
Dim param1, param2 As SqlCeParameter
param1 = New SqlCeParameter("Name", uname.Text)
param2 = New SqlCeParameter("Password", pwd.Text)
command.Parameters.Add(param1)
command.Parameters.Add(param2)
Dim reader As SqlCeDataReader = command.ExecuteReader
If (reader.Read = True) Then
role = reader.GetString(1)
Else
MsgBox("Invalid Login")
End If
I have this code is working. What to write for
Private Sub frmlogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

I would recommend trying the DataReader's HasRows property to determine if one or more rows was returned to the DataReader object.
if (reader.HasRows)
{
reader.Read();
role = reader.GetString(1)
}
else
{
// invalid login
}

Not sure I completely understand your question, but if the table is empty then reader.Read() would evaluate to False.
I think what you want is a SQL Statement checking the Count of the users table.
Something like
command = New SqlCeCommand("SELECT COUNT(Name) as NameCount FROM Users", con)
Then you would evaluate the count by doing something like
Dim reader as SqlCeDataReader = command.ExecuteReader()
While(reader.Read())
if reader("NameCount") = 0 then
'Redirect to Admin Form
else
'Run all your current logic here to find the user from the DB
end if
End While

Related

How to delete a row in sql using vb.net

Sorry if its easy or basic i am brand new to sql and tables so im just trying to figure it out
Basically im trying to delete a row that the user selects
By having them click on a row then clicking a delete button but i don't know how that should look ive tried a few different ways but none of them seem to work.
No error comes up but it just dosen't delete the row
Private Sub DeleteSelectedUsers()
Dim connection As SqlConnection = New SqlConnection()
connection.ConnectionString = "Data Source=GERARD-PC\SQLEXPRESS; Initial Catalog=TestDB;User ID=AccountsUser;Password=password123"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("Delete * from dgrdUsers.SelectedRows(0).Cells", connection)
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim username As String = dgrdUsers.SelectedRows(0).Cells.Item("Username").Value.ToString()
If (MessageBox.Show(Me, "Do you want to delete user " & username & "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
DeleteSelectedUsers()
End If
Catch ex As Exception
End Try
End Sub
Any ideas?
The syntax required to delete a row in the database table requires at least three parts.
The DELETE command
The FROM statement to identify the table where the delete action should occur
The WHERE condition to identify the record (or records) to delete
So it is a string like this: DELETE FROM tablename WHERE condition
and applied to your code you get this.
Private Sub DeleteSelectedUsers(userName as String)
Using connection As SqlConnection = New SqlConnection()
connection.ConnectionString = "...."
connection.Open()
Dim cmd As SqlCommand = New SqlCommand _
("DELETE FROM Table WHERE userName = #user", connection)
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = userName
cmd.ExecuteNonQuery()
End Using
End Sub
(Table and UserName are fantasy names because we don't know what is the actual schema of your database)
Other things I have changed:
The connection is created inside a using block to be sure a proper
closure and dispose happens even in case of errors
The name of the user to remove should be passed as parameter to the
function
No need to use an adapter when you just need to execute a single
SqlCommand
The query doesn't concatenate strings to build the command but use a
parameter added to the command itself and specifying a type for the
data matching the type on the database table

VB: SQL Query return result to textbox

In short, I am working on a program that will add/edit entries to an SQL database.
One of the features for this program is that it, if given the account ID number, will look up the name under that account with that given ID. This is what I am having trouble with.
General Format:
Objective: SQL Query that will return string to textbox
AcctID => field in table with account number
AcctName => field in table with account name
txtbx_accountName => textbox I need the name returned to
NOTE:
This is all nested in a generic Try-Catch statement with error
handling.
This is all inside a Click event handler for a button.
This is all done in Visual Studio 2015
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ""
myConn.Open() ' Open the connection
myCmd = myConn.CreateCommand()
' Build the query with the account number as paramter
myCmd.CommandText = "SELECT AcctName FROM DataSetTable WHERE (AcctID = #incomingAcctID)"
' Add the parameter so the SqlCommand can build the final query
myCmd.Parameters.Add(New SqlParameter("#incomingAcctID", (CInt(txtbx_accountNum.Text))))
' run the query and obtain a reader to get the results
Dim reader As SqlDataReader = myCmd.ExecuteReader()
' check if there are results
If (reader.Read()) Then
' populate the values of the controls
txtbx_accountName.Text = reader(0)
End If
' Close all connections
myCmd.Dispose()
myConn.Close() ' Close connection
myConn.Dispose()
i am not pro but i do like this,sorry if this not helped you:
if your Stored procedure is created to add and edit than write this and call it where you want to add:
private sub NAME(ByVAL Parameter1 name as integer,
ByVAL Parameter2 name as string,
ByVAL Parameter3 name as boolean)
Dim strConn As String = ConfigurationManager.ConnectionStrings("databaseXYZ").ConnectionString
Dim myConn As New SqlConnection(strConn)
Dim myCmd As SqlCommand
try
myConn.Open()
sqlCommand = New SqlCommand("PRCEDURE_NAME", myConn )
sqlCommand.CommandType = CommandType.StoredProcedure
dim param as new System.Data.SqlClient.SqlParameter
param.parameterName="#send_parameter1"
param.Direction = ParameterDirection.Input
param.Value = send_parameter1
dim param1 as new System.Data.SqlClient.SqlParameter
param1.parameterName="#send_parameter2"
param1.Direction = ParameterDirection.Input
param1.Value = send_parameter2
sqlCommand.Parameters.Add(Param)
sqlCommand.Parameters.Add(Param1)
sqlCommand.ExecuteNonQuery()
catch ex as exception
throw
End Try
myConn.Close()
myConn = Nothing
end sub
I'm a dummy!!!
Here is the solution, for all interested parties.
Click Event Handler (w/ nested Try-Catch):
txtbx_accountName.Text = DataSetTableAdapter.SearchNameQuery(CInt(txtbx_accountNum.Text)).ToString
SearchNameQuery:
SELECT AcctName FROM DataSetTable WHERE AcctID = #incomingAcctID
More notes on this:
- The dataset is already included in the project

How to get a string value from a sql table in visual basic

Basically I have a login system and want to add access rights. In order to do this I want my code to refer to my SQL database, return the value of access and then an if statement which would then direct the user according to their access rights. I believe the issue is when: If access = "Admin", as All I get now is the error message. I can't find out how to refer Admin to Admin in the SQL table.
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
'connection to the database
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
Dim access As String
'data location
connection.ConnectionString = ("Data Source=CHRISTIAN;Initial Catalog=Complete;Integrated Security=True")
'sql statement
command.CommandText = "SELECT Access_Level FROM [User] WHERE Username= '" & txtUsername.Text & "'AND Password='" & txtPassword.Text & ";'"
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(dataset, "0")
access = CType(command.ExecuteScalar(), String)
Try
If access = "Admin" Then
MenuAdmin.Show()
Me.Hide()
ElseIf access = "User" Then
Menu1.Show()
Me.Hide()
Else
MsgBox("Please try again, wrong username or password entered!")
txtPassword.Clear()
txtUsername.Clear()
'txtUsername.Focus()
End If
Catch ex As Exception
End Try
Thanks for any help
If it is simply a case of connecting to the database to retrieve the value of a column called "access" you will need to look into ADO.NET. Its a rather big subject but there will be plenty of examples if you have a quick Google.
Basic Microsoft ADO.Net example
Using a dataset just to return this one field seems unnecessary if you aren't going to do anything else with the table. Try something like
SqlDataReader reader=command.ExecuteReader();
string access="";
if(reader.HasRows){
reader.Read();
access=reader.IsDBNull(0) ? "" : reader.GetString(0);
}
else{
//Handle unauthorised access
}
reader.Close();
reader.Dispose();

Updating database with BindingSource data

This is my first post in here, but this forum already helped me a lot.
First, sorry for my English, i'm from Brazil and i'm trying to write without a translator.
I'm developing a software for a supermarket, but i'm having problems with the connection to the database. I'm trying to make all the connections and transactions programmatically (DataSets, BindingSources and so).
I've already managed to connect with SQL Server Express 2008, using a Function ("consulta") inside a Module ("db"):
Dim ad As SqlDataAdapter = New SqlDataAdapter
Function consulta(ByVal tabela As String, Optional opt As Boolean = False, Optional optparam As String = "") As DataSet
Dim ds As New DataSet
Try
Dim connstring As String = "Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=SysMarket;Persist Security Info=True;User ID=admin;Password=XXXXXX"
Dim conObj As New SqlConnection(connstring)
Dim sql As String
If opt = True Then
sql = "SELECT * FROM " & tabela & " " & optparam
Else
sql = "SELECT * FROM " & tabela
End If
Dim cmd As SqlCommand = New SqlCommand(sql, conObj)
ad.SelectCommand = cmd
conObj.Open()
ad.Fill(ds, tabela)
ad.Dispose()
cmd.Dispose()
conObj.Close()
Return ds
Catch ex As Exception
MessageBox.Show("Erro na consulta" & vbCrLf & ex.InnerException.ToString, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
ds.Clear()
Return ds
End Try
End Function
And this is a part of the main code where I make a SelectQuery and put into a BindingSource:
Dim ds As DataSet = db.consulta("departamentos")
Private Sub cad_departamento_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BindingSource1.DataSource = ds
BindingSource1.DataMember = "departamentos"
TextBox1.DataBindings.Add("Text", BindingSource1, "id")
TextBox2.DataBindings.Add("Text", BindingSource1, "departamento")
End Sub
But my problem is when I have to Update the database, by adding, editing or deleting some item from BindingSource. Because in the Module I've closed the connection to the SQL Server. So I will need reopen this connection and then, somehow "read" the DataSet with the change and Update the database?
Someone could explain this to me or show me a example?
Thank you.
You will use a data adapter to save the data, just as you used one to retrieve the data. You will have to create an InsertCommand if you want to insert new records, an UpdateCommand if you want to update existing records and a DeleteCommand if you want to delete existing records. You can write those yourself or, if the conditions are right, you can use a command builder to do it for you.
If your query is based on a single table and you want to insert/update all the columns you retrieve back to that same table then a SqlCommandBuilder may be your best bet. You simply pass in the query and the command builder will use it to generate the action commands. That gives you limited flexibility but if you're just doing single-table operations then you don't need that added flexibility.
Such a method might look something like this:
Public Sub SaveChanges(tableName As String, data As DataSet)
Dim query = "SELECT * FROM " & tableName
Using adapter As New SqlDataAdapter(query, "connection string here")
Dim builder As New SqlCommandBuilder(adapter)
adapter.Update(data, tableName)
End Using
End Sub
I did what you said, but when I open the Form again, the new data are not there.
I made some changes in the code, perhaps because it did not work
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
BindingSource1.EndEdit()
ds.AcceptChanges()
db.SaveChanges("departamentos", "INSERT INTO departamentos VALUES('', " & TextBox2.Text & ")", ds)
ds = db.consulta("departamentos")
End Sub
And the code in the Module
Function SaveChanges(tableName As String, query As String, data As DataSet)
Using adapter As New SqlDataAdapter(query, "Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=SysMarket;Persist Security Info=True;User ID=admin;Password=XXXXX")
Dim builder As New SqlCommandBuilder(adapter)
adapter.Update(data, tableName)
Return True
End Using
End Function

Validate username and password in Microsoft VIsual Studio

I am having trouble validating a username and password when someone clicks a button. I have two text boxes named user_logon_id and user_password.
I have a table called MyUsers that I suppose to verify that both the username (user_logon_id) and password (user_password) are in the same row. If they do not match, it's supposed to notify the user. If it does match then direct them to userAdmin.aspx.
I am using Microsoft Visual Studio 2008. I am really new to this and would really like to get a grasp on this. I do not need to worry about encrypting the password.
Can you run this in the debugger and verify that the query is returning a row?
Some suggestions:
Consider parameterizing your query like this:
Dim conn As New SqlConnection(_connectionString)
conn.Open()
Dim s As String = "SELECT user_password FROM MyUsers WHERE user_logon_id = #user_login_id"
Dim cmd As New SqlCommand(s)
cmd.Parameters.Add("#user_login_id", Me.user_logon_id.Text)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Hash the password in some way
Consider selecting from the database table where the username and password match. If the result is one record the login succeeded.
Dim s As String = "SELECT userid FROM MyUsers WHERE user_logon_id = #user_login_id and user_password=#user_password"
Full code
Protected Sub butSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butSubmit.Click
Dim myReader As Data.SqlClient.SqlDataReader
Dim mySqlConnection As Data.SqlClient.SqlConnection
Dim mySqlCommand As Data.SqlClient.SqlCommand
'Establish the SqlConnection by using the configuration manager to get the connection string in our web.config file.
mySqlConnection = New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString1").ToString())
Dim sql As String = "SELECT userid FROM MyUsers WHERE user_logon_id = #user_login_id and user_password=#user_password"
mySqlCommand = New Data.SqlClient.SqlCommand(sql, mySqlConnection)
cmd.Parameters.Add("#user_login_id", Me.user_logon_id.Text)
cmd.Parameters.Add("#user_password", Me.user_password.Text)
Try
mySqlConnection.Open()
myReader = mySqlCommand.ExecuteReader()
If (myReader.HasRows) Then
'Open page with users and roles
Dim message As String = "Correct password"
Dim style As MsgBoxStyle = MsgBoxStyle.OkOnly
Dim title As String = "Authenticated"
MsgBox(message, style, title)
End If
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
If Not (myReader Is Nothing) Then
myReader.Close()
End If
If (mySqlConnection.State = Data.ConnectionState.Open) Then
mySqlConnection.Close()
End If
End Try
End Sub