OledbException Data type mismatch in criteria expression - sql

I'm getting a OledbException Data type mismatch in the criteria expression, at ad.Fill(xDataset, "TblMaster").
I'm using an Access database and Telerik Reporting.
This is my code
Public Sub TanggalX()
conn.Open()
Dim str9 As String = "Select * From TblMaster Where Tanggal='" & Me.DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")) & "'"
ad = New OleDb.OleDbDataAdapter(str9, conn)
xDataset.Clear()
ad.Fill(xDataset, "TblMaster")
obj_RepDoc = New Report1
obj_RepDoc.DataSource = (xDataset)
Me.ReportViewer1.Report = obj_RepDoc
Me.ReportViewer1.RefreshReport()
Me.Show()
conn.Close()
End Sub
Please help me this is my last problem for this project.

You should use # instead of ' for Date/Time fields.
Dim str9 As String = "SELECT * FROM TblMaster WHERE Tanggal=#" & Me.DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")) & "#"

My guess is that TblMaster.Tangall is of type Date and you are specifying it as a string in the WHERE clause of your SQL select command.
Try the following:
using (OleDbCommand comm = new OleDbCommand())
{
var parameter =comm.Parameters.AddWithValue("#tangall", Me.DateTimePicker1.Value);
parameter.OleDbType = OleDbType.DBDate;
using (var ad = new OleDbDataAdapter(comm))
{
... //do your stuff here
}
}

I think InBetween is right. You can also convert the string to date inside the SQL statement instead of using parameters by replacing your SQL statement with this:
Dim str9 As String = "Select * From TblMaster Where Tanggal=CDate('" & Me.DateTimePicker1.Value.ToString() & "')"

Related

How to concat to access cell using vb.net

I want to concat(add to what already exist) to an access cell using the text from a vb.net textbox. I tried using UPDATE but I'm getting a syntax error. This is what I tried so far
Dim ds As New DataSet()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\equip_full.mdb;Jet OLEDB:Database Password=matt"
Dim db As String = "Update INTO Equipment set TypeItem = ISNULL(TypeItem, '') & #EquipmentItem WHERE EquipmentCat = #category"
Using cn As New OleDbConnection(ConnectionString)
Using cmd = New OleDbCommand(db, cn)
cn.Open()
cmd.Parameters.Add("#EquipmentItem", OleDbType.VarWChar).Value = Form4.TextBox1.Text & ";"
cmd.Parameters.Add("#category", OleDbType.VarWChar).Value = Me.item_text.Text
Using reader = cmd.ExecuteReader()
'some code...
End Using
End Using
End Using
The correct syntax for an Update query is
UPDATE tablename SET field=value, field1=value1,.... WHERE condition
Then you need to remove that INTO that is used in the INSERT queries
Dim db As String = "Update Equipment set TypeItem = .... " &
"WHERE EquipmentCat = #category"
After fixing this first syntax error, then you have another problem with ISNull
ISNull is a boolean expression that return true or false.
If you want to replace the null value with an empty string you need the help of the IIF function that you could use to test the return value of ISNull and prepare the base string to which you concatenate the #Equipment parameter.
Something like this
Dim db As String = "Update Equipment " & _
"set TypeItem = IIF(ISNULL(TypeItem),'', TypeItem) & #EquipmentItem " & _
"WHERE EquipmentCat = #category"

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()

the user must match to the 3 fields

Dim elem As String
elem = "Grade School"
Dim v As Integer
v = 0
Dim con As New SqlConnection("SERVER=ANINGDZTS-PC;DATABASE=AEVS;Trusted_Connection = yes;")
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department, VotersID = '" & elem & "''" & txt_PwordElem.Text & "'AND Voted ='" & v & "'", con)
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
Try
If (sdr.Read() = False) Then
high()
Else
MessageBox.Show("WELCOME!")
elemBallot.Show()
Me.Hide()
End If
Catch EX As Exception
MsgBox(EX.Message)
End Try
End Sub
this code is not working, an error appear," An expression of non-boolean type specified in a context where a condition is expected, near ','."
Instead of trying to create your SQL query via concatenating strings, which is prone to errors, a much better way is to use parametrized query. Change your SqlCommand declaration to
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department = #Department AND VotersID = #VotersID AND Voted = #Voted", con)
cmd.Parameters.AddWithValue("#Department", elem)
cmd.Parameters.AddWithValue("#VotersID", txt_PwordElem.Text)
cmd.Parameters.AddWithValue("#Voted", v)
Bonus: Avoid SQL Injection
P.S. Please don't forget to close your Reader and Connection after the use.
P.P.S. If you simple need to make sure that specific row in table "tbl_Voter" exists or not based on your parameters (which is, judging by the code what you're doing) - using DataReader is overkill. Consider query like SELECT 1 FROM tbl_Voter ... and use of ExecuteScalar to check returned value for Nothing

ORA-01704: string literal too long when updating a record

I am trying to update an Oracle Database record and i keep getting this error:
ORA-01704: string literal too long 5
I looked up that error and it seems that i have a limit of 4000 charters since i am using Oracle 10g. However, the prgblem is that its the same exact data i am putting back into that record so that is why i am unsure as to why its giving me that error for the same amount of data i took out of it.
Here is my update code:
Dim myCommand As New OracleCommand()
Dim ra As Integer
Try
myCommand = New OracleCommand("Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = '" & theData & "' WHERE EID = '81062144'", OracleConnection)
ra = myCommand.ExecuteNonQuery()
OracleConnection.Close()
Catch
MsgBox("ERROR" & Err.Description & " " & Err.Number)
End Try
I'm not sure if there is anything special you have to do in order to update a clob or not.
I extract the clob like so:
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
And it works just fine extracting but just not putting it back in.
Any help would be great!
David
UPDATE CODE
Dim OracleCommand As New OracleCommand()
Dim myCommand As New OracleCommand()
Dim ra As Integer
While dr.Read()
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
theData = Replace(theData, "…", " ")
Try
Dim strSQL As String
isConnected2 = connectToOracleDB2()
OracleConnection.Close()
If isConnected2 = False Then
MsgBox("ERRORConn: " & Err.Description & " " & Err.Number)
Else
myCommand.Connection = OracleConnection2
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'ERROR', COMPLETE_DATE = '', DATA = :1 WHERE EID = '" & theEID & "'"
myCommand.CommandText = strSQL
Dim param As OracleParameter = myCommand.Parameters.Add("", OracleDbType.Clob)
param.Direction = ParameterDirection.Input
param.Value = theData
Application.DoEvents()
ra = myCommand.ExecuteNonQuery()
Application.DoEvents()
OracleConnection2.Close()
Application.DoEvents()
End If
Catch
MsgBox("ERROR: " & Err.Description & " " & Err.Number)
OracleConnection2.Close()
End Try
End While
dr.Close()
OracleConnection.Close()
Do not hardcode the value into your SQL query. Instead wrap it in a parameter. Like this:
Dim strSQL As String
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = :1 WHERE EID = '81062144'"
myCommand.CommandText=strSQL
And then:
Dim param As OracleParameter=myCommand.Parameters.Add("",OracleDbType.Clob)
param.Direction=ParameterDirection.Input
param.Value=blob.Value
You can (and should) of course add all other variables (status code, complete date, eid) of your query as parameters, too, instead of hard-coding them into your SQL.
Varchar2 in sql has a limitations of 4000 characters. This limitation does not apply to the data stored in a varchar column. You need to convert this to pl\sql or specify some other column type. ( I am not a php expert. So I cannot provide any sample, just the reason for your error).
Essentially you need to specify the data type as clob while executing the bind query. Otherwise it will default to varchar2 and the above limitation will apply.

Selecting an integer from an Access Database using SQL

Trying to select an integer from an Access Database using an SQL statement in VB
Dim cmdAutoTypes As New OleDbCommand
Dim AutoTypesReader As OleDbDataReader
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = '" & cboTypeIds.Text & "'"
AutoTypesReader = cmdAutoTypes.ExecuteReader
Error message says: "OleDbException was unhandled: Data type mismatch in criteria expression." and points to the AutoTypesReader = cmdAutoTypes.ExecuteReader line
Rather make use of OleDbParameter Class
This will also avoid Sql Injection.
You don't need the quotes in the query string. You're searching for a number, not a string.
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text
Hi In access SQL you can't use single quote around your Integer type.
so
command text will be.. "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text & " and .... "
In Access SQL, don't quote numeric constants.
And test whether IsNull(cboTypeIds). You can't do what you were planning to do until a value has been chosen.
Do not use string concatenation when you build your SQL query, use parameters instead.
Dim cmd As OledbCommand = Nothing
Dim reader as OleDbDataReader = Nothing
Try
Dim query As String = "SELECT * FROM AutoTypes WHERE TypeId = #Id"
cmd = New OledbCommand(query, connection)
//adding parameter implicitly
cmd.Parameters.AddWithValue("#Id", cboTypeIds.Text)
reader = cmd.ExecuteReader()
Catch ex As Exception
Messagebox.Show(ex.Message, MsgBoxStyle.Critical)
End Try
You can also explicitly state the parameter data type.
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = cboTypeIds.Text
Hope this helps.