Click here to Skip to main content
15,895,870 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I can import my non English characters from excel (Sheet3 that named "Goods") to SQL by VBA code but after that my characters changed to Question mark (?) and I lost them actually.

how can I fix my VBA code.

What I have tried:

VB
Private Sub CommandButton1_Click()
   Dim con As ADODB.Connection
   Dim iRowNo As Integer
   Dim sGoodsName, sGoodsCode, sunit As String

   Set con = New ADODB.Connection
   con.Open "driver={SQL Server};" & "Server=DESKTOP-P163904;authenticateuser=True;database=sample1"

   iRowNo = 2
   Do Until Worksheets("Goods").Cells(iRowNo, 1) = ""
      sGoodsName = Worksheets("Goods").Cells(iRowNo, 1)
      sGoodsCode = Worksheets("Goods").Cells(iRowNo, 2)
      sunit = Worksheets("Goods").Cells(iRowNo, 3)

      con.Execute "insert into test3 (GoodsName, GoodsCode, unit) values ('" & sGoodsName & "', '" & sGoodsCode & "', '" & sunit & "')"
      iRowNo = iRowNo + 1
   Loop

   con.Close
   Set conn = Nothing

End Sub
Posted
Updated 11-Aug-17 12:04pm
v3

First of all, check that the target column is defines as NVARCHAR (nchar and nvarchar (Transact-SQL) | Microsoft Docs[^]).

After that, use prefix N before the literal values. In other words:
VB
con.Execute "insert into test3 (GoodsName, GoodsCode, unit) values (N'" & sGoodsName & "', N'" & sGoodsCode & "', N'" & sunit & "')"


As a side note, to protect the database from SQL injection and to ensure that apostrophe is correctly inserted, if present in the data, you should use parameters. Have a look at Command Object Parameters | Microsoft Docs[^]
 
Share this answer
 
Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900