I have a critical requirement , need to update a table in Sql server from access through forms and buttons,
When a user clicks the button in the form he should be able to update the record which is already existing in the database.
For Eg: table has columns -EmployeeID , Employee Name, Employee Location
EmployeeID Values
-----
1001|
2301|
3212|
Suppose a user wants to update value of EmployeeName alone not employee location ,he should be able to do that in some case employee.
update table set EmployeeName=#New_employee_name , Employee Location=#New_employee_location where EmployeeID=#Employee_ID
This should be driven through vb. net program inorder to update the user input value in the database.
I would recommend you create a Stored Procedure on the SQL Server, here is an example:
CREATE PROCEDURE sp_UpdateEmployeeByID
(
#ID int,
#TitleID int,
#FirstName nvarchar(255),
#LastName nvarchar(255)
)
AS
BEGIN
SET NOCOUNT ON;
UPDATE Employee SET
TitleID = #TitleID,
FirstName = #FirstName,
LastName = #LastName
WHERE ID = #ID
END
Using stored procedures rather than ad-hoc SQL protects you from SQL Injection attacks plus there are performance benefits.
Then using VB.Net you will want to call the Stored Procedure, passing in the updated employee values.
Public Sub UpdateEmployeeByID(Byval ID As Int32, Byval TitleID As Int32, Byval FirstName As string, Byval LastName As string)
Dim connString As String = ConfigurationManager.AppSettings("ConnectionString")
Dim conn As New SqlConnection(connString)
conn.Open()
Dim sqlCommand As new SqlClient.SqlCommand("sp_UpdateEmployeeByID", conn)
sqlCommand.CommandType = CommandType.StoredProcedure
sqlCommand.Parameters.AddWithValue("#ID", ID)
sqlCommand.Parameters.AddWithValue("#TitleID", TitleID)
sqlCommand.Parameters.AddWithValue("#FirstName", FirstName)
sqlCommand.Parameters.AddWithValue("#LastName", LastName)
Try
sqlCommand.ExecuteNonQuery()
Catch ex As SqlException
'Handle SQL exceptions
Catch ex As Exception
'Handle exceptions
Finally
'clean up resources that access Data
If IsNothing(sqlCommand) = False Then
sqlCommand.Dispose()
sqlCommand = Nothing
End If
conn.Close()
End Try
End Sub
Related
I'm working on a webapp project. I've added a function for the teacher to add exams. What I need is:
When the teacher adds a new exam record using a DetailsView, the date should be automatically inserted into the date columnn in the exams table in the database.
Here is the code :
Protected Sub DetailsView1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles DetailsView1.ItemInserted
Dim conn As New SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings("MCQQUIZZES").ConnectionString
Dim sql As String = "INSERT INTO [Exams] VALUES(#Dateadded) "
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#Dateadded", Date.Now.ToString)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
the error massege :
Column name or number of supplied values does not match table definition.
any help??
Provide Column Names in Insert command
INSERT INTO Table(Col1, Col2) VALUES (value1,value2)
Please change the query in code.
INSERT INTO [Exams] (date) VALUES(getdate())
I'm trying to get this query to work but it's not working:
strQuery = "Insert Into StudentInfo (StudentSurname, StudentNumber) Values (#Surname, #StudentNo) Where StudentName=#Name"
Any help is appreciated.
If you are inserting new record, the WHERE clause doesn't make any sense. It isn't valid SQL syntax either.
You can try the following:
strQuery = "Insert Into StudentInfo (StudentName, StudentSurname, StudentNumber) Values (#Name, #Surname, #StudentNo)"
To update an existing record, use the UPDATE statement:
strQuery = "Update StudentInfo SET StudentName=#Name, StudentSurname=#Surname WHERE StudentNumber=#StudentNo"
The WHERE clause should have StudentNumber (instead of StudentName) since that would be unique for each student. Names may be duplicate and would result in updating the wrong records.
The following shows performing an update using OleDb data provider, if you are working with SQL-Server change OleDb to SqlClient e.g. SqlConnection and SqlCommand. Note how the command text is set which requires Framework 3.5 or higher.
Public Sub UpdateRow(
ByVal StudentSurname As String,
ByVal StudentNumber As Integer,
ByVal StudentName As String)
Using cn As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("", cn)
cmd.CommandText =
<SQL>
UPDATE StudentInfo
SET
StudentSurname = #StudentSurname,
StudentNumber = #StudentNumber
WHERE
StudentName = #StudentName
</SQL>.Value
cmd.Parameters.AddWithValue("#StudentSurname", StudentSurname)
cmd.Parameters.AddWithValue("#StudentNumber", StudentNumber)
cmd.Parameters.AddWithValue("#StudentName", StudentName)
cn.Open()
Dim Affected As Integer = CInt(cmd.ExecuteNonQuery())
If Affected <> 1 Then
' we have a problem
Else
' update successful
End If
End Using
End Using
End Sub
I'm using SQL Server as my DBMS and I have 2 tables namely Person and Voter.
Person has these columns:
PersonId (int, primary key auto-increment int_identity),
FirstName (nvarchar(50))
LastName (nvarchar(50))
Voter has these columns:
VoterPersonId (int, foreign key)
VoterPlace (nvarchar(50))
These 2 tables are related. For 1 person there can only be 1 voter place. So you may call it a one is to one relationship. I created 2 tables because there are also people who aren't voters that I must include in my database and I don't want to create null values so I made a separate table which is the 'voter' table. Basically, I wanted to know the number registered voters and non-voters in our city. Now, I have created a 'save' button in VB.NET and used the following code to insert information into my tables:
Dim sql As New SQLControl
Private Sub cmdSave_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
sql.con.Open()
Using cmdPerson As New SqlClient.SqlCommand("INSERT INTO Person(FirstName, LastName) VALUES('" & txtFirstName.Text & "', '" & txtLastName.Text & "')", sql.con)
cmdPerson.ExecuteNonQuery()
End Using
Using cmdVoter As New SqlClient.SqlCommand("INSERT INTO Voter(VoterPlace) VALUES('" & txtVoterPlace.Text & "')", sql.con)
cmdVoter.ExecuteNonQuery()
End Using
sql.con.Close()
End Sub
Now, my problem is I don't know how to transfer the value of 'PersonId' primary key which is auto-increment in_identity into 'VoterPersonId' the moment I click on the 'save' button. Is it possible? Can you please help me on this matter? I would really appreciate it.
You can execute both queries in a single stored procedure
CREATE PROCEDURE InsertPerson
#firstname varchar(50),
#lastname varchar(50),
#voterPlace varchar(50)
AS
declare #newid int
INSERT INTO Person(Firstname, Lastname) VALUES (#firstname, #lastname)
SELECT #newid = SCOPE_IDENTITY()
INSERT INTO Voter(VoterPersonId, VoterPlace) VALUES ( #newid, #voterPlace)
You can use a stored procedure but you certainly don't have to. The principle is still the same though. You execute the insert to the parent table and then use the SCOPE_IDENTITY function to get the auto-generated ID. You would then use an output parameter to get that value back into your app so that you can include it in the next insert to the child table, e.g.
Using connection As New SqlConnection("connection string here"),
parentCommand As New SqlCommand("INSERT INTO Parent (ParentName) VALUES (#ParentName); SET #ParentId = SCOPE_IDENTITY();", connection),
childCommand As New SqlCommand("INSERT INTO Child (ParentId, ChildName) VALUES (#ParentId, #ChildName)", connection)
With parentCommand.Parameters
.AddWithValue("#ParentName", parentName)
.Add("#ParentId", SqlDbType.Int).Direction = ParameterDirection.Output
End With
connection.Open()
Dim transaction = connection.BeginTransaction()
Try
parentCommand.ExecuteNonQuery()
With childCommand.Parameters
.AddWithValue("#ParentId", parentCommand.Parameters("#ParentId").Value)
.AddWithValue("#ChildName", childName)
End With
childCommand.ExecuteNonQuery()
transaction.Commit()
Catch
transaction.Rollback()
End Try
End Using
Can anyone tell me how I would go about checking if a database and tables exists in sql server from a vb.net project? What I want to do is check if a database exists (preferably in an 'If' statement, unless someone has a better way of doing it) and if it does exist I do one thing and if it doesn't exist I create the database with the tables and columns. Any help on this matter would be greatly appreciated.
Edit:
The application has a connection to a server. When the application runs on a PC I want it to check that a database exists, if one exists then it goes and does what it's supposed to do, but if a database does NOT exist then it creates the database first and then goes on to do what it's supposed to do. So basically I want it to create the database the first time it runs on a PC and then go about it's business, then each time it runs on the PC after that I want it to see that the database exists and then go about it's business. The reason I want it like this is because this application will be on more than one PC, I only want the database and tables created once, (the first time it runs on a PC) and then when it runs on a different PC, it sees that the database already exists and then run the application using the existing database created on the other PC.
You can query SQL Server to check for the existence of objects.
To check for database existence you can use this query:
SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase'
To check for table existence you can use this query against your target database:
SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U'
This below link shows you how to check for database existence is SQL Server using VB.NET code:
Check if SQL Database Exists on a Server with vb.net
Referenced code from above link:
Public Shared Function CheckDatabaseExists(ByVal server As String, _
ByVal database As String) As Boolean
Dim connString As String = ("Data Source=" _
+ (server + ";Initial Catalog=master;Integrated Security=True;"))
Dim cmdText As String = _
("select * from master.dbo.sysdatabases where name=\’" + (database + "\’"))
Dim bRet As Boolean = false
Using sqlConnection As SqlConnection = New SqlConnection(connString)
sqlConnection.Open
Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
Using reader As SqlDataReader = sqlCmd.ExecuteReader
bRet = reader.HasRows
End Using
End Using
End Using
Return bRet
End Function
You could perform the check in another way, so it's done in a single call by using an EXISTS check for both the database and a table:
IF NOT EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase')
BEGIN
-- Database creation SQL goes here and is only called if it doesn't exist
END
-- You know at this point the database exists, so check if table exists
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U')
BEGIN
-- Table creation SQL goes here and is only called if it doesn't exist
END
By calling the above code once with parameters for database and table name, you will know that both exist.
Connect to the master database and select
SELECT 1 FROM master..sysdatabases WHERE name = 'yourDB'
and then on the database
SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'yourTable'
i dont know the exact vb syntax but you only have to check the recordcount on the result
For tables and other objects inside a database, I usually do it this way but it's really personal preference.
IF OBJECT_ID('dbo.blah') IS NOT NULL
BEGIN
END
For VB.NET, I'd wrap this in a stored procedure and call that. I'm sure there are also ways to do this with Linq.
You can use This query for check database
IF DB_Id('YourDatabaseName') IS NOT NULL
BEGIN
PRINT 'DB EXISTS'
END
ELSE
BEGIN
PRINT 'DB NOT EXISTS'
END
Friend Function CheckDatabaseExists(server As String, database As String) As Boolean
Dim connString As String = "Data Source=" + server + ";Initial Catalog=master;Integrated Security=SSPI"
Dim cmdText As String = "select * from master.dbo.sysdatabases where name='" + database + "'"
Dim bRet As Boolean = False
Using sqlConnection As SqlConnection = New SqlConnection(connString)
sqlConnection.Open
Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
Using reader As SqlDataReader = sqlCmd.ExecuteReader
bRet = reader.HasRows
End Using
End Using
End Using
Return bRet
End Function
Public Function SQLDatabaseExist(ByVal DefaultConnectionString As String, ByVal DataBaseName As String) As Boolean
Try
'CREATE DATABASE
Dim SqlString As String = ""
SqlString = "SELECT CASE WHEN EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'" & DataBaseName & "') THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END"
Dim ExcRet As Integer = 0
Using connection As New SqlConnection(DefaultConnectionString)
Dim command As New SqlCommand(SqlString, connection)
command.Connection.Open()
ExcRet = command.ExecuteScalar()
command.Connection.Close()
command.Dispose()
End Using
Return ExcRet
Catch ex As Exception
Return False
End Try
End Function
I'm getting an error when the 'insertcommand' is executed telling me that I'm missing the parameters for the stored procedure. Do I need to put the parameter names in the Sql statement after the procedure as if I were calling it in SQL? I saw an example online that just added the parameters like I have here, but this doesn't work? I also put the sql state for the stored procedure below the 'AddRepair Sub'
Public Shared Sub AddRepair(ByVal repair As ClubRepair)
Dim conn As SqlConnection = ClubRentalsDB.getconnection
Dim insertcommand As New SqlCommand("AddRepair", conn)
insertcommand.Parameters.AddWithValue("#Name", repair.Name)
insertcommand.Parameters.AddWithValue("#ID", repair.MemberID)
insertcommand.Parameters.AddWithValue("#Phone", repair.PhoneNumber)
insertcommand.Parameters.AddWithValue("#Email", repair.Email)
insertcommand.Parameters.AddWithValue("#Work", repair.WorkToBeDone)
insertcommand.Parameters.AddWithValue("#Specification", repair.Specification)
insertcommand.Parameters.AddWithValue("#SoonestDate", repair.SoonestCompletion)
insertcommand.Parameters.AddWithValue("#PromisedDate", repair.DatePromised)
insertcommand.Parameters.AddWithValue("#ClubType", repair.TypeOfClub)
insertcommand.Parameters.AddWithValue("#GripType", repair.TypeOfGrip)
insertcommand.Parameters.AddWithValue("#NumOfClubs", repair.NumOfClubs)
insertcommand.Parameters.AddWithValue("#SpecialInstructions", repair.SpecialInstructions)
Try
conn.Open()
insertcommand.ExecuteReader()
Catch ex As Exception
MessageBox.Show(messageBad & ex.ToString)
Finally
conn.Close()
End Try
End Sub
USE [ClubRentals]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[AddRepair] (#Name Varchar(50), #ID varchar(20),
#Phone varchar(50),#Email varchar(50), #Work varchar(20),#Specification varchar(MAX),
#SoonestDate date, #PromisedDate Date, #ClubType varchar(50), #Griptype varchar(50),
#NumOfClubs int, #SpecialInstructions varchar(MAX)) as
Insert into ClubRepair(Member_Name,Member_ID,Phone,Email,WorkToBeDone,Specification,
SoonestPossibleCompletion,DatePromised,TypeOfClub, TypeOfGrips ,NumOfClubs,
SpecialInstructions)
values(#Name, #ID, #Phone, #Email, #Work, #Specification,
#SoonestDate, #PromisedDate, #ClubType, #GripType,
#NumOfClubs,#SpecialInstructions)
GO
Confirm that every parameter value you are setting is not Nothing. Parameters with no value can cause the missing parameter error. There's a two-argument version of If() that helps:
insertcommand.Parameters.AddWithValue("#Specification", If(repair.Specification, ""))
this will return repair.Specification if it is not Nothing, and "" otherwise.
also, you should consider using Parameters.Add().Value() instead of .AddWithValue(), like so:
insertcommand.Parameters.Add("#ClubType", SqlDbType.VarChar, 50).Value = If(repair.TypeOfClub, "")
This is really useful when you're working with types other than string.
Try setting sqlcommand commandtype to storedprocedure.
make sure to respect case sensitivity, for an example
insertcommand.Parameters.AddWithValue("#GripType", repair.TypeOfGrip)
is wrong
insertcommand.Parameters.AddWithValue("#Griptype", repair.TypeOfGrip)
is right