Related
I have created a macro in Excel to import and export data from SQL Server. However, when I try to export data, it throws an error
[Microsoft][ODBC SQL Server Driver][SQL Server]
Error converting data type varchar to numeric
The code worked fine when I was exporting integer numbers. The error came up when I tried exporting real numbers.
Dim gil, gibnr, gul, fil, fibnr, ful, qil, qibnr, qul, xil, xibnr, xul, oil, oibnr, oul, cil, cibnr, cul, nil, nibnr, nul, bul, hul, lul, indul As Long
conn.Execute "insert into dbo.Intl_LL (UWU,OBU,Profile_ID, Insured_name, Claim_number,Claim_desc, Event_Name, UY, AY, AQ, Date_of_loss, Region, CCY, Policy_number, Branch, LE, MPL,Claim_alert_email, Comments, [Large Profile Flag], [Earmark Flag], [Tracked for Qtrly dev], [Gross Incurred], [Gross IBNR], [Gross Ultimate], [FAC Incurred], [FAC IBNR], [FAC Ultimate], [QS Incurred],[QS IBNR],[QS Ultimate],[XOL Incurred],[XOL IBNR],[XOL Ultimate],[Ceded OTH Incurred],[Ceded OTH IBNR],[Ceded OTH Ultimate],[Ceded Total Incurred],[Ceded Total IBNR],[Ceded Total Ultimate],[Net Incurred],[Net IBNR],[Net Ultimate],[Booked Ultimate],version)" & _
"values ('" & sUWU & "', '" & sOBU & "','" & sProfile & "', '" & sInsured & "','" & sClaim & "','" & sClmdesc & "','" & sEvent & "','" & sUY & "','" & sAY & "','" & sAQ & "','" & sDOL & "','" & sRegion & "','" & sCCY & "','" & sPolnum & "','" & sBranch & "','" & sLE & "','" & sMPL & "','" & sClaimalert & "','" & sComm & "','" & sLargeF & "','" & sEarF & "','" & sTrackF & "','" & gil & "', '" & gibnr & "','" & gul & "','" & fil & "','" & fibnr & "','" & ful & "','" & qil & "','" & qibnr & "','" & qul & "','" & xil & "','" & xibnr & "','" & xul & "','" & oil & "','" & oibnr & "','" & oul & "','" & cil & "','" & cibnr & "','" & cul & "','" & nil & "','" & nibnr & "','" & nul & "','" & bul & "', '" & ver & "')"
I have ensured that the variables that have Long data type in VBA are numeric(7, 11) type in SQL Server.
Feel free to ask for more information about the problem. Thanks.
MySQL must assume the values are supposed to be the same type as the "mycol" column and silently converts them. - It does the same when you try to compare an INT to a string.
However, you should try not to quote values that are supposed to be numbers. Even if MySQL does automatically convert some of them, it costs a few cycles and the behavior may not be consistent.
Bottom line: always leave numbers unquoted, and only quote strings and dates.
I am new in vb.net i have sqlcommand string as shown
Dim query As [String] = "insert into tblDefProducts( Creation_Date, Product_code,line_item_id , item_name , category_id , subcategory_id , Gender ,LifeType, supplier_id , Acquire_type , Purchase_type , Manufacture_type , Pur_Con_Unit, Pur_Con_factor ,Tax_At_Retail_Price, Sale_Tax ,Average_cost ,Product_group_id,status,Technical_details )
values( " & DateTimePicker2.Value.ToString() & ",'" & PCode_TXT.Text & "','" & LineItem_TXT.Text & "' , '" & PName_TXT.Text & "','" & CategoryM_CMB.Text & "','" & CategoryS_CMB.Text & "','" & ProductGender_TXT.Text & "', '" & ProductLifeT_CMD.Text & "','" & ProductSupplier_CMB.Text & "','" & PAquireType_CMB.Text & "', '" & PPurchaseType_CMB.Text & "','" & PManufacturing_CMB.Text & "','" & PConnUnit_CMB.Text & "' ," & Convert.ToInt32(PConFactory_TXT.Text) & "," & Convert.ToInt32(PSalesTaxPurchase_TXT.Text) & "," & Convert.ToInt32(PSalesTaxSales_TXT.Text) & "," & Convert.ToInt32(PPRICE_TXT.Text) & " , " & PTypeA & " , " & pActive & ",'" & PTechnicalDetail_TXT.Text & "')"
2 Problems
Input string is not in a correct format second insertion of datetime value from datetimepicker1 to database column creation_date have datatype DateTime but datetimepicker gives value #1/1/1900#
also have to parse using sql
Using string contaternation to pass parameters is not a good idea for a number of reasons: Its vulnerable to SQL Injection attacks, more prone to errors and harder to read and maintain.
In you question the problem is likly due to missing '' around some of your values.
Imagine if you only wanted the user to be able to update certain fields in your table but the user typed something like "Hello', ReadOnlyField = 'World" into a text box which you then concaternate into your query. The ReadOnlyField world be updated. With parameters this would be prevented.
If you use parameters instead you don't need to wory about '' as parameters are typed variables and not strings.
You also don't need to convert everything to a string as most .NET primitves has SQL equivalents.
See here for examples and documentation on VB.Net SqlCommand.Parameters
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters%28v=vs.110%29.aspx
If you have a database columns, which is not of type string, int or any other primitive, you should not pass the value without using the ado.net parameter system (you should never!). Because if you use 01.01.2015 instead of System.DateTime, the database has to parse the date from string to datetime/timestamp, which is often cause issues, because the date is not in a structured form and converting fails. In general, never pass parameter with string concation. One additional reason is, that this allows very easy sql injection and is not as stable as using the ado.net parameter system.
One thing that I see is
Dim query As [String] = "insert into tblDefProducts( Creation_Date, Product_code,line_item_id , item_name , category_id , subcategory_id , Gender ,LifeType, supplier_id , Acquire_type , Purchase_type , Manufacture_type , Pur_Con_Unit, Pur_Con_factor ,Tax_At_Retail_Price, Sale_Tax ,Average_cost ,Product_group_id,status,Technical_details )
values( '" & DateTimePicker2.Value.ToString("yyyyMMdd") & "','" & PCode_TXT.Text & "','" & LineItem_TXT.Text & "' , '" & PName_TXT.Text & "','" & CategoryM_CMB.Text & "','" & CategoryS_CMB.Text & "','" & ProductGender_TXT.Text & "', '" & ProductLifeT_CMD.Text & "','" & ProductSupplier_CMB.Text & "','" & PAquireType_CMB.Text & "', '" & PPurchaseType_CMB.Text & "','" & PManufacturing_CMB.Text & "','" & PConnUnit_CMB.Text & "' ," & Convert.ToInt32(PConFactory_TXT.Text) & "," & Convert.ToInt32(PSalesTaxPurchase_TXT.Text) & "," & Convert.ToInt32(PSalesTaxSales_TXT.Text) & "," & Convert.ToInt32(PPRICE_TXT.Text) & " , " & PTypeA & " , " & pActive & ",'" & PTechnicalDetail_TXT.Text & "')"
I am trying to write a form to insert data into multiple tables within a single database.
I know you can't do that through a single Insert into statement so I read that I should create a transaction and include multiple Insert statements. I keep getting 3134 run time error on my second insert statement. Here is the code:
Private Sub cmdAdd_Click()
DBEngine.BeginTrans
CurrentDb.Execute "INSERT into Names(StudentId, FirstName, MiddleName, LastName) VALUES (" & Me.txtStudentId & ",'" & _
Me.txtFirstName & "','" & Me.txtMiddleName & "','" & Me.txtLastName & "')"
CurrentDb.Execute "INSERT into Homeroom(StudentId, Grade, Homeroom_Primary, Name-Homeroom_Primary_Teacher) " & _
"VALUES (" & Me.txtStudentId & ",'" & Me.txtGrade & "','" & Me.txtHomeroom & "','" & Me.txtTeacher & "')"
CurrentDb.Execute "INSERT into [Ridgeview Math](StudentId, ExportGrade, DateTaken, SS, PR) VALUES (" & _
Me.txtStudentId & ",'" & Me.txtGrade & "',#" & Me.txtMathdate & "#,'" & Me.txtMathSS & "','" & Me.txtMathPR & "')"
CurrentDb.Execute "INSERT into [Ridgeview Reading](StudentId, ExportGrade, DateTaken, RSS, RPR, RIRL) " & _
"VALUES (" & Me.txtStudentId & "','" & Me.txtGrade & "',#" & Me.txtReadingdate & "#,'" & Me.txtReadingSS & "','" & _
Me.txtReadingPR & "','" & Me.txtReadingIRL & "')"
CurrentDb.Execute "INSERT into CompassGroup(StudentId, CompassGroup) VALUES (" & Me.txtStudentId & _
"," & Me.txtCompassGroup & ")"
DBEngine.CommitTrans
End Sub
Am I doing something wrong with the nested Insert statements?
This is all tied to a form where the variables are created and the data is entered. The first Insert statement gives me no errors. Please let me know if you need more information.
Bracket the field name Name-Homeroom_Primary_Teacher because of the dash.
I suggest you use a string variable to hold the statement text, Debug.Print the string, and then Execute it.
Dim strInsert As String
strInsert = "INSERT into Homeroom(StudentId, Grade, Homeroom_Primary, [Name-Homeroom_Primary_Teacher]) " & _
"VALUES (" & Me.txtStudentId & ",'" & Me.txtGrade & "','" & Me.txtHomeroom & "','" & Me.txtTeacher & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailonerror
If case of errors, you can go to the Immediate window (Ctrl+g) to inspect the statement text. And you can copy that text, create a new query in the query designer, switch to SQL View, paste in the text, and test the statement there.
Also the approach you're using requires a whole lot of concatenating. Other options you can consider are: parameter queries; adding rows to DAO Recordsets.
following is the code which is use to enter datagridview items into the table.
Dim X As DataGridViewRow
grnno = 123123
glocation = txtlocation.Text
gsupplier = txtsupplier.Text
greceivedby = txtreceivedby.Text
greceiveddate = txtreceiveddate.Text
grn_status = cmbstatus.SelectedItem
ggrossamt = txtgrossamt.Text
gdiscountamount = txtdiscount.Text
gtotalnetamount = txttotalnet.Text
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) values('" & glocation & "','" & gsupplier & "','" & greceivedby & "','" & greceiveddate & "','" & grn_status & "'," & ggrossamt & "," & gdiscountamount & "," & gtotalnetamount & " )"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "','" & X.Cells(6).Value & "','" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
Next
the error is in the 2nd insert statement, it gives error cannot convert string to integer.. the cells from x.cell(6) are of integer type and in database also its integer type, now I want to ask should I enclose it in single quotations or not, as enclosing in single quotations give such errors like syntax '' and in double quotations it gives like cannot convert string to int type.please tell where I am doing wrong.
First of all use parametrized queries! It is safer and also more readable. You are passing some value as string but should be integer.
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) _
values(#glocation, #gsupplier, #greceivedby, #greceiveddate, #grn_status, #ggrossamt, #gdiscountamount, #gtotalnetamount)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#glocation", glocation)
sqlcmd.Parameters.AddWithValue("#gsupplier", gsupplier) //and so on
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) _
VALUES(#grnno, #item_code, #description, ...)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#grnno", grnno)
sqlcmd.Parameters.AddWithValue("#item_code", CType(X.Cells(0).Value, Integer)) //cast to proper type
sqlcmd.ExecuteNonQuery()
Next
Remove the single quote marks ''
For example (and referring only to x.cell(6) as per your post) use " & X.Cells(6).Value & "
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & X.Cells(6).Value & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
You may also need to cast it (assuming it's always going to have a numeric value)
" & CInt(X.Cells(6).Value) &"
I will assume you know of SQL injection and this method of updating a database is generally 'outdated' and 'bad practice' now and you should use parameters instead...
Updated
Since there is a possibility of a null (and you want it to be a 0 where this is the case), you could use something like (not tested as I'm not a VB person)
dim cellSix as integer
if IsNothing(X.Cells(6).Value then
cellSix = 0
else
cellSix = CInt(X.Cells(6).Value)
end if
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & cellSix & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
Or, to keep the code shorter you could use the IIF
cellSix = IIf(isnothing(CInt(X.Cells(6).Value)), 0, CInt(X.Cells(6).Value))
am new to vb.net i have a project vb.net connect to access 2003 database and i want to insert data through vb.net to access data base am using Sql commands here is the code bt it's not working for me
cmd.CommandText = "INSERT INTO info(nam, employed, ple, mertebe, navonishan, sermoche, moche, dxindin, dbemoche, brwaname)" + " VALUES (" & Me.NamTextBox.Text & ",'" & CDate(Me.EmployedDateTimePicker.Text) & "','" & CInt(Me.PleTextBox.Text) & "','" & CInt(Me.MertebeTextBox.Text) & "','" & Me.NavonishanTextBox.Text & "','" & CDate(Me.SermocheDateTimePicker.Text) & "','" & CInt(Me.MocheTextBox.Text) & "','" & CByte(Me.DxindinCheckBox.Checked) & "','" & CByte(Me.DbemocheCheckBox.Checked) & "','" & Me.BrwanameTextBox.Text & "' );"
Use parametrized query.
cmd.CommandText = "INSERT INTO info(nam, employed, ple, mertebe, navonishan, " & _
"sermoche, moche, dxindin, dbemoche, brwaname) VALUES (" & _
"?,?,?,?,?,?,?,?,?,?)"
cmd.Parameters.AddWithValue("#p1", Me.NamTextBox.Text)
cmd.Parameters.AddWithValue("#p2", Convert.ToDateTime(Me.EmployedDateTimePicker.Text))
cmd.Parameters.AddWithValue("#p3", Convert.ToInt32(Me.PleTextBox.Text))
cmd.Parameters.AddWithValue("#p4", Convert.ToInt32(Me.MertebeTextBox.Text))
cmd.Parameters.AddWithValue("#p5", Me.NavonishanTextBox.Text)
cmd.Parameters.AddWithValue("#p6", Convert.ToDateTime(Me.SermocheDateTimePicker.Text))
cmd.Parameters.AddWithValue("#p7", Convert.ToInt32(Me.MocheTextBox.Text))
cmd.Parameters.AddWithValue("#p8", Me.DxindinCheckBox.Checked)
cmd.Parameters.AddWithValue("#p9", DbemocheCheckBox.Checked)
cmd.Parameters.AddWithValue("#p10", Me.BrwanameTextBox.Text)
A part from the string concatenation, in this way you don't risk to pass a value intended to be a number or a date with the wrong formatting rules (your numeric or date values should not be enclosed in single quotes).
Of course this avoid also the Sql Injection problems stated by other (Cody Gray) in comment