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
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 using a bulkcopy to a temp table that then will be used to MERGE to the main table. All is working but when I try dropping my temp table, I get an error saying 'Table '#temptable' does not exist'
Basically I do the following.
'get data from excel to a datatable.
Dim cmd As New OleDbCommand(sqlstring, excelConnection)
dt.Load(cmd.ExecuteReader())
'create sql connection
Using sqlcon As SqlConnection =
New SqlConnection(ConfigurationManager.ConnectionStrings("SQLCON").ConnectionString)
sqlcon.Open()
'create temp table
Dim sqlcmd As New SqlCommand("create table #tbltemp (ID int, FirstName nvarchar(50),LastName nvarchar(50),JobDesc nvarchar(50))", sqlcon)
sqlcmd.ExecuteNonQuery()
Try
'start bulcopy
Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(sqlcon)
'map columns
Dim mapID As New SqlBulkCopyColumnMapping("ID", "ID")
bulkcopy.ColumnMappings.Add(mapTMID)
Dim mapFName As New SqlBulkCopyColumnMapping("FirstName", "FirstName")
bulkcopy.ColumnMappings.Add(mapFName)
Dim mapLName As New SqlBulkCopyColumnMapping("LastName", "LastName")
bulkcopy.ColumnMappings.Add(mapLName)
End Using 'end bulkcopy using
'Inserts new records to main from temptable
Dim mergesql As String = "merge into dbo.Main as Target " & _
"using #tbltemp as Source " & _
"on " & _
"(Target.ID = Source.ID) " & _
"when not matched then " & _
"insert (ID,FirstName,LastName) values (Source.ID,Source.FirstName,Source.LastName);"
sqlcmd.CommandText = mergesql
sqlcmd.ExecuteNonQuery()
'Clean up stuff
cmd.CommandText = "DROP TABLE [#tbltemp]"
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
'close sql con
sqlcon.Close()
End Try
'close excel con
excelConnection.Close()
End Using ' end using sqlcon
Like I said, everything seems to be working except for dropping the table. Does this means that temp table has been dropped automatically?
I tried running some tests and searched around but no luck.
cmd is the OleDbcommand associated with you excelconnection and not a SqlCommand associated with your Database connection.
Incidently, I use this technique all the time and you can also create the temporary table as...
Select Top 0 * Into #tbltemp From dbo.Main
This save on defining the columns in a static create table statement.
Also if you are working with temp tables a lot within the same connection then you can check it exists and drop it using...
If Object_Id('TempDB..#tbltemp') Is Not Null Drop Table #tbltemp
SQL Server will automatically drop temp tables when the connection closes, so there isn't actually any need for you to do this.
Not sure why it is failing on the drop part though. You might not have the right permissions.
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 got this error upon testing on how to update the particular column in the latest database entry by clicking a button. Before, i set the update statement as
Dim statement As String = "UPDATE tblPatientInfo SET bottle_used = #bottlecount"
statement &=" WHERE room_number =1"
But all entries in the database are updated, thats why Im trying to use ORDER BY ID DESC, ID is the primary id. The program should get the latest database entry and it will only update the bottle_used. Upon using it, I got an OleDbException.
This is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'====test number of bottles=============
Form5.lblBottle.Text = Form5.lblBottle.Text + 1
Dim statement As String = "UPDATE tblPatientInfo SET bottle_used = #bottlecount ORDER BY ID DESC"
Dim cmd As New OleDbCommand
With cmd
.Connection = Conn
.CommandType = CommandType.Text
.CommandText = statement
.Parameters.AddWithValue("#bottlecount", Form5.lblBottle.Text)
Conn.Open()
.ExecuteNonQuery()
End With
Conn.Close()
End Sub
Any help would be appreciated. thanks!
It seems you want to update the row with the maximum ID value. The DMax function should make this easy.
UPDATE tblPatientInfo
SET bottle_used = #bottlecount
WHERE ID = DMax('ID', 'tblPatientInfo')
basically you cannot add an ORDER BY clause directly in an update statement. The only way you can to create an update statement with order by is to create a select subquery with order by clause. Example,
UPDATE messages
SET status=10 WHERE ID in
(
SELECT ...
FROM ...
WHERE ...
ORDER BY priority
)
maybe you want this,
UPDATE tblPatientInfo
SET bottle_used = #bottlecount
WHERE ID =
(
SELECT MAX(ID) maxID
FROM tblPatientInfo
WHERE room_number = 1
)
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