Getting error on inserting date into sql database? - sql

I'm inserting record into database but is getting error on the paremeter "Date". Any thoughts would be good.
myConnection.Open()
Dim sqlQry As String = "INSERT INTO MasterLabNumber (LabNumber, Location, Date)" + "VALUES(#LabNumber, #Location, #Date)"
Dim str As String
str = "SELECT * FROM MasterLabNumber WHERE (LabNumber = " & TextBox1.Text & ")"
Dim d As System.DateTime = DateTime.Now.ToString("yyyy/MM/dd")
Dim cmd As OleDbCommand = New OleDbCommand(sqlQry, myConnection)
cmd.Parameters.AddWithValue("#LabNumber", TextBox1.Text)
cmd.Parameters.AddWithValue("#Location", ComboBox1.Text)
cmd.Parameters.AddWithValue("#Date", d)
cmd.ExecuteNonQuery() <-- gets error here relating to adding the parameter date.

Yeah, that's cause Date is a reserve word which you are using in your insert statement. You need to escape it like below using []
INSERT INTO MasterLabNumber (LabNumber, Location, [Date])
Your insert statement should become
Dim sqlQry As String = "INSERT INTO MasterLabNumber (LabNumber, Location, [Date]) VALUES(#LabNumber, #Location, #Date)"

Related

How to check and update existing record date when new row is entered else add new row

enter code hereSql table columns ( Clientid, Client_Status, Notes, Startdt,Enddt, Entrydt, Entryid) My current code adds data rows from UI, user enters Start date, Status and notes
with Enddt defaulting to 9/9/9999. I need to change my code to -whenever a new reord/Status is enrtered check for existing record/Status with that Clientid,
If records exists update the EndDt of existing record from 9/9/9999 to StartDt-1( new record StartDt) which is entered from Interface. Else enter as new client.
Private Sub BtnAddStatus_Click(sender As System.Object, e As System.EventArgs) Handles BtnAddStatus.Click
Clientid = txtboxClid.Text
Client_Status = cbboxStatus.Text
StartDt = txtStartDt.Text
notes = txtnote.Text
conn = New SqlClient.SqlConnection("conneting string")
Dim theQuery As String = "select * from Table name where Clientid = #Clientid and EndDt = '9/9/9999'"
Dim cmd2 As SqlCommand = New SqlCommand(theQuery, conn)
cmd2.Parameters.AddWithValue("#Clientid", txtboxClid.Text)
conn.Open()
If txtboxClid.Text.Trim <> "" And txtStartDt.Text.Trim <> "" Then
Using reader As SqlDataReader = cmd2.ExecuteReader()
If reader.HasRows Then
Dim query2 As String = "UPDATETable name SET ([EndDt] = SELECT (todate(StartDt)-1) FROM Table name WHERE Clientid = #Clientid and EndDt ='9/9/9999')"
reader.Close()
End If
End Using
Dim query As String = "INSERT INTO Table name (Clientid, Client_Status, Notes, Startdt,Enddt, Entrydt, Entryid) VALUES ('" & Clientid & "','" & Client_Status & "','" & Notes & "','" & StartDt & "',getdate(),'" & UName & "');"
Dim command = New SqlCommand(query, myconn)
command.ExecuteNonQuery()
MsgBox("Status Added ")
conn.Close()
Call GetInfoClientid()
End If
End If
End Sub
The simple reason is the fact that you are not executing the command stored in query2, but your code has other errors and someone potentially catastrophic.
First, you should always use parameters and never concatenate strings to build sql commands. If you concatenate strings you enable a simple trick called Sql Injection that allows anyone to hack your database.
Second you could directly call the Update without checking for the presence of a previous related record. The update will simply return with 0 record changed if the record doesn't exist.
Finally, the disposable objects like the connection should be created when needed and disposed as soon as possible. The Using Statement serves for this purpose.
Dim Client_Status As String = cbboxStatus.Text
Dim notes As String = txtnote.Text
' Suppose Clientid is a number not a string
Dim Clientid as Integer = Convert.ToInt32(txtboxClid.Text)
' Suppose you have a date in your database, not a string
Dim StartDt as DateTime = Convert.ToDateTime(txtStartDt.Text)
' Calculate here the previous ending date
Dim PrevEnd As DateTime = StartDt.AddDays(-1)
' Conventional max end date
Dim maxEndDate as DateTime = new DateTime(9999,9,9)
If txtboxClid.Text.Trim <> "" And txtStartDt.Text.Trim <> "" Then
' Create here the connection to dispose on exit from the using statement
Using conn As SqlConnection = New SqlClient.SqlConnection("conneting string")
conn.Open()
' USE PARAMETERS EVERYWHERE. DO NOT USE STRINGS TO FIND A DATE
Dim query2 As String = "UPDATE [Table name] SET [EndDt] = #newEnd
WHERE Clientid = #Clientid
AND EndDt = #maxEnd"
Dim command = New SqlCommand(query2, conn)
command.Parameters.Add("#Clientid", SqlDbType.Int).Value = Clientid
command.Parameters.Add("#newEnd", SqlDbType.Date).Value = newEnd
command.Parameters.Add("#maxEnd", SqlDbType.Date).Value = maxEndDate
command.ExecuteNonQuery()
' Prepare the insert.
Dim query As String = "INSERT INTO [Table name]
(Clientid, Client_Status, Notes, Startdt,Enddt, Entrydt, Entryid)
VALUES
(#Clientid, #status,#Notes,#StartDt,#maxDate,getdate(), #UName);"
command.Parameters.Clear()
command.Parameters.Add("#Clientid", SqlDbType.Int).Value = Clientid
command.Parameters.Add("#status", SqlDbType.NVarChar).Value = Client_Status
command.Parameters.Add("#notes", SqlDbType.NVarChar).Value = notes
command.Parameters.Add("#startdt", SqlDbType.Date).Value = StartDt
command.Parameters.Add("#maxDate", SqlDbType.Date).Value = maxEndDate
command.Parameters.Add("#uname", SqlDbType.NVarChar).Value = uname
command.CommandText = query
command.ExecuteNonQuery()
End Using
Call GetInfoClientid()
End If
Notice that I pass parameters of the appropriate type for what I suppose is the type of your columns. It is common error to think that a string like '9/9/9999' is a date. But for a computer program this is a string and if you want to use as a date we need to convert it to a proper date. This conversion more often than not results in wrong data passed to the database engine.
This should have been handled in stored procedure. But, since you have done most of the things here, I would suggest a minor change on this which would work. First, Remove the check before update and change the update query to:
Dim query2 As String = "UPDATE Table name SET [EndDt] = todate(#StartDt)-1 WHERE Clientid = #ClientId and EndDt ='9/9/9999'"
Dim cmd As SqlCommand = new SqlCommand(query2, vbConn);
cmd.AddParam(“#StartDt”,StartDt)
cmd.AddParam("#Clientid",ClientId)
(assuming clientid to be varchar, since you have used single quotes on insert statement)
Also, write executenonquery() statement for query2.

getting error : Conversion failed when converting character string to smalldatetime data type. when querying again DB

I am getting an error when trying to insert into a table. As the error shows I know is because of the smalldatetime field. But I have tried several different things From other posts and its not working. Plus when I'm reading from the same table I use the same format for smalldatetime and it works. code show below. Any help would be really appreciated.
Code when trying to Insert a new row
.vb.net
Dim conn As String = "Your Connection String"
'Dim querystring As String = "INSERT INTO 'Where SupID='" & supervisor & "' Order By EmpNum"
Dim querystring As String = "INSERT INTO [AttendanceDB].[dbo].[tblAbsences]([fldEmployeeID] " & _
",[fldAbsentDate],[fldAbsentCode],[fldRuleViolationWarningType],[fldRuleViolationIssueDate] " & _
",[fldLOAEndDate]) VALUES('23','11-06-2014','NA','NULL','NULL','NULL')"
Using connection As New SqlConnection(conn)
Dim command As New SqlCommand(querystring, connection)
connection.Open()
Try
command.ExecuteNonQuery()
Catch ex As Exception
connection.Close()
End Try
End Using
I have also tried this code in SQL Management Studio
INSERT INTO [AttendanceDB].[dbo].[tblAbsences]([fldEmployeeID],
[fldAbsentDate],[fldAbsentCode],[fldRuleViolationWarningType],
[fldRuleViolationIssueDate],[fldLOAEndDate])
VALUES ('23','11-06-2014','NA','NULL','NULL','NULL')
This is the code that works when im reading from the same table when databinding to ViewGrid
Dim startdate As String = txtcalendarstart.Text
Dim enddate As String = txtcalendarstop.Text
startdate = startdate.Replace("/", "-")
enddate = enddate.Replace("/", "-")
Dim SqlDataSource2 As SqlDataSource = New SqlDataSource()
SqlDataSource2.ID = "SqlDataSource2"
Page.Controls.Add(SqlDataSource2)
SqlDataSource2.ConnectionString = "Data Source=SVR-SQLDB2;Initial Catalog=AttendanceDB;Integrated Security=True"
SqlDataSource2.SelectCommand = "SELECT * FROM [tblAbsences] WHERE [fldAbsentDate] BETWEEN '7-03-2014' AND '8-21-2014' ORDER BY [fldEmployeeID]"
GridView1.DataSource = SqlDataSource2
GridView1.DataBind()

Getting Primary key values (auto number ) VB

I have a database on Access and I want to insert into 2 tables
ReportReq
req_sysino
I want to get the last value of primary key (auto numbered) and insert it into req_sysino
, I am stuck with this code and I dont know how to proccess
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select ##REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
this is my insert code that should generate autonumber
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (#reqNUM,#reqName,#reqDescrip,#reqcolumns,#reqfilters,#reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("#reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("#reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("#reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("#reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("#reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("#reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("#reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("#reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Immediately after you ExecuteNonQuery() your INSERT INTO ReportReq ... statement you need to run a
SELECT ##IDENTITY
query and retrieve its result, like this
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT ##IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()

How to Insert data while Copying data in other Table

My problem is, in one button (click event) I need to Copy a data in Table1 (the ToolName) to Table2 (into ToolName) and insert a description to the same row.
Table1
ID - ToolName - Quantity
Table2
ID - ToolName - Description
here`s my codes
Dim sqlquery As String = "INSERT INTO Table2 (ToolName) SELECT ToolName FROM Table1 WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString & "' INSERT INTO Table2 (Description) VALUES ('" & TextBox1.Text & "')"
Dim cmd As New OleDbCommand(sqlquery, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox(" succesfully", vbInformation)
con.Close()
Parametrized queries have two main advantages:
Security: It is a good way to avoid SQL Injection vulnerabilities
Performance: If you regularly invoke the same query just with different parameters a parametrized query might allow the database to cache your queries which is a considerable source of performance gain.
Extra: You won't have to worry about date and time formatting issues in your database code. Similarly, if your code will ever run on machines with a non-English locale, you will not have problems with decimal points / decimal commas.
Try like this
Dim sqlquery As String= "INSERT INTO Table2 (ToolName,Descrption) SELECT ToolName,#Desc FROM Table1 WHERE ID = #Id"
Dim cmd As New OleDbCommand(sqlquery, con)
cmd.Parameters.Add("#Desc", SqlDbType.VarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Id", SqlDbType.VarChar, 50).Value = DataGridView1.CurrentRow.Cells(0).Value.ToString
con.Open()
cmd.ExecuteNonQuery()
MsgBox("succesfully", vbInformation)
con.Close()
Change Query syntax like below
Dim sqlquery As String = "INSERT INTO Table2 (ToolName)
SELECT ToolName FROM Table1
WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString & "';
INSERT INTO Table2 (Description) VALUES ('" & TextBox1.Text & "')"
I think nothing is wrong in query just missing ; between 2 insert query.
Just break it down into two separate updates based on what you already have, use the following code and just pass the ToolName into your update statements
Dim Table_ As String = "getToolName"
Dim query As String = "SELECT ToolName FROM Table1 WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString
Dim cmd As New OleDbCommand(query, con)
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds, Table_)
Dim dt As DataTable = ds.Tables(Table_)
Dim ToolName As String = dt.Rows(0)(0).ToString()

Sql statement returning incorrect data

I am confused as to why my SQL select statement is returning incorrect data. In my database the value is 009698 and it is returning 9698. Could someone shed some light as to why this would be happening.
It is an MS Access 2010 database and the column is text and the size is 6.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
DBConnection.connect()
sql = "SELECT MAX([Request no]) from Requests WHERE Customer = '" & cmbCustomer.Text & "' "
Dim cmd As New OleDb.OleDbCommand
Dim id As Integer
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
While dr.Read()
id = CInt(dr.Item(0))
id = (id) + 1
End While
'MessageBox.Show("00" & id)
'sql = "INSERT INTO Requests ([Request no], Customer) VALUES ('" & id & "', '" & cmbCustomer.Text & "')"
cmd.Dispose()
'dr.Close()
oledbCnn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
You are treating the returned value as integer so '009698' and '9698' are the same values in this context.
If you want to later convert it to a six-digit string, you can do:
Dim stringId as String
While dr.Read()
id = CInt(dr.Item(0))
id = (id) + 1
stringId = id.ToString().PadLeft(6, "0"c)
End While
Since the field is text, why not use the GetString function on the DataReader.
Dim id As String
While dr.Read
''The string value returned from the database
Dim stringID = dr.GetString(0)
''convert the string to an int and add 1
Dim numericID = CInt(stringID) + 1
''convert the number back to a string with leading 0
id = numericID.ToString.PadLeft(stringID.Length, "0")
End While
I'm assuming you're trying to get the string value from a db, convert it to a number, add one, and then convert it back to the string format with leading zeros.