I have the following scenario-
User may enter text in any language in the text box and need to store it in my database along with language name. Following is the code for this on button Update
Dim conStr As String = "Dsn=search;database=search;description=search;option=0;port=0;server=localhost;uid=root;CharacterSet=UTF8;"
Dim s As String = txtLanguage.Text '<----"音読み現代仮名遣い人名用漢字"
mySQL = "INSERT INTO multi_language(language, characters)" & _
" VALUES ('Japanese', '" & s & "')"
con.ConnectionString = conStr
con.Open()
cmd = New OdbcCommand(mySQL, con)
cmd.ExecuteNonQuery()
con.Close()
screen short for running the query
after clicking button the text in the Textbox becomes '??????'
and the data inserted in the data base is like the following
Language | characters
--------------------------
Japanese | ?????
My table structure is
CREATE TABLE multi_language
(
id INTEGER NOT NULL AUTO_INCREMENT,
language VARCHAR(30),
characters TEXT,
PRIMARY KEY(id)
) ENGINE=INNODB CHARACTER SET = utf8;
when i execute the query directly in the query browser then it will executed properly,
whats wrong with my coding? what i need to add to get proper result?
This is the screenshot for the comparison of insert from the
I am also suffering from a similar situation, i solved it in a different way as follows:
while inserting Use your Query as :
Dim s As String = txtLanguage.Text '<----"音読み現代仮名遣い人名用漢字"
mySQL = "INSERT INTO multi_language(language, characters)" & _
" VALUES ('Japanese', '" & encodeUTF(s) & "')"
Encode the string before inserting
Public Function encodeUTF(ByVal inputString As String) As String '<-- function for encoding the input string
Dim byt() As Byte = uni.GetBytes(inputString)
encodeUTF = ""
For Each b As Byte In byt
encodeUTF &= b & ","
Next
Trim(Replace(encodeUTF, ",", ""))
End Function
decode the string before retriving
Public Function decodeUTF(ByVal inputString As String) As String '<-- function for decoding the input string
Dim strs() As String
strs = inputString.Split(",").ToArray
Dim temp(strs.Length) As Byte
Dim i As Integer
For i = 0 To strs.Length - 2
temp(i) = Byte.Parse(strs(i))
Next
decodeUTF = uni.GetString(temp)
decodeUTF = decodeUTF.Substring(0, Len(decodeUTF) - 1)
End Function
While Retrieving this text to a text box you can use your query as :
mySQL = "Select language, characters from multi_language"
Reader = objdb.GetDataReader(mySQL)'<--- is a class function which returns the datareader
If Reader.HasRows = True Then
Reader.Read()
txtlang.Text = objOdbcDataReader.Item("language")'<--- display the selected language
txtchar.Text = objOdbcDataReader.Item("characters ")'<--- display the selected characters
End If
You can try this proposed solution,
If your application want to save data in to database in multiple language, make sure your database stores data in UTF-8 and also the connection to your database is in UTF-8 (commonly people forget this).
Make sure to Execute this query when establishing a connection:
mysql_query("SET NAMES utf8");
In Your application end, where user input data, set the accept-charset attribute on your forms.
<form accept-charset="utf-8">
Set appropriate meta tags for your site:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
or Serve your sites with an appropriate HTTP header:
header('Content-Type: text/html; charset=utf-8');
So overall the problem is, everything is not in UTF-8, If you keep everything in UTF-8, usually don't need to worry about anything.
Refer Strategy for supporting unicode & multi language in PHP5
Storing and displaying unicode string (हिन्दी) using PHP and MySQL
perhaps you should use parametrized query (which anyway is always a better choice than string concatenation, which is susceptible to sql injection)
modify your query to use parameters (I am not sure if for mysql the #param is correct syntax):
"INSERT INTO multi_language(language, characters) VALUES ('Japanese', #val)"
then add parameter to your query:
cmd = New OdbcCommand(mySQL, con)
cmd.Parameters.AddWithValue("#val", txtLanguage.Text)
cmd.ExecuteNonQuery()
con.Close()
Related
I have an SSRS report requirement to generate json string through custom code by concatenating all the report Parameter name and value pairs. To achieve this I can explicitly access each report parameters and concatenate to generate the expected text. But , I am trying to find if there is anyway to loop through the parameter collection and generate it dynamically , so that there is no need to update the function whenever a new parameter is added. Thank you!!
OK, so due to the fact that the parameters collection is not very well supported via custom code, this will only work once the report is deplyed to the server. This makes it tricky to debug but we can work around that by hardcoding a parameter whilst we test.
This answer might look long but in fact it's pretty quick to do.
To get started Create a report and add your parameters
In my sample report I had two parameters,
CountryID (text - multivalue)
PeriodID (integer - single value)
Deploy the report now even though it's not finished we need to deploy now for the rest to work.
So the first things we need to do is get a list of parameters. We can do this if we know the report's full path. We will hardcode this value for now but make it dynamic before we finish.
Create a dataset called dsParameters and set the query to the following.
DECLARE #pNameList varchar(1000) =''
SELECT #pNameList = eachParam.value('Name[1]', 'VARCHAR(250)') +'|' + eachParam.value('Type[1]', 'VARCHAR(250)') + CASE #pNameList WHEN '' THEN '' ELSE ',' + #pNameList END
FROM (
SELECT CONVERT(XML, c.Parameter) AS pxml
FROM ReportServer.dbo.Catalog c
WHERE c.[Path] = #ReportPath
) a
CROSS APPLY pxml.nodes('//Parameters/Parameter') ( eachParam )
SELECT #pNameList as pNameList
This will return someting like
PeriodID|Integer,CountryID|String
Now right-click the dataset, choose "dataset properties" then "Parameters".
Set the #ReportPath parameter value to the path and report name of your report. You can get this ReportServer.dbo.catalog in the Path column, it will look something like ="/Sales Reports Folder/My Sales Report" . Note the forward slashes.
We will come back to the hardcoded value later once it's all working.
Next, go to the report's properties and click the Code tab.
Paste in the following two functions.
Public Function GetParameterValues(ByVal parameter as Parameter, ByVal pType as string) as String
Dim s as String = ":["
If parameter.IsMultiValue then
For i as integer = 0 to parameter.Count-1
if i >0 then
s = s + ","
end if
if pType = "String" then
s = s + """" + CStr(parameter.Value(i)) + """"
else
s = s + CStr(parameter.Value(i))
end if
Next
Else
s = s + CStr(parameter.Value)
End If
Return s + "]"
End Function
Public Function GetJSON(ByVal parameters as Parameters, pNameTypeList as String) as string
' pass in a list of parameter names
' for each name GetParameterValues
' append the result to json txt
Dim pList() AS String = Split(pNameTypeList, ",")
Dim pParts() AS String
Dim i as Integer
Dim pName as string
Dim pType as string
Dim json as String ="{"
While i <= pList.Length - 1
pParts = Split(pList(i), "|")
pName = pParts(0)
pType = pParts(1)
if i >0 then
json = json + ","
end if
json = json & """" & pName & """"
json &= GetParameterValues(parameters(pName), pType)
json = json & vbcrlf
i += 1
End While
json = json & "}"
Return json
End Function
The first function accepts a parameter object and data type and loops thru the parameter values to return a single line such as "CountryID":["89","94"]
The second function takes the parameters collection and a list of parameter names and types in the form Name1|Type1,Name2|Type1. It starts with the json "header", repeatdly calls the first function adding comma's as required and then closes the json.
The output will be something like this...
{"PeriodID":[2020300]
,"CountryID":["89","94"]
}
NOTE I have only defined quoting for the String type, you may need to adjust to suit your needs.
Finally (almost) create a textbox and set the value expression to
=Code.GetJSON(Parameters,
First(Fields!pNameList.Value, "dsParameters")
)
Here's the final report output...
FINALLY We need to make that dataset parameter dynamic. Go back to the dataset's parameters and set the #ReportPath parameter value to
=Globals!ReportFolder & "/" & Globals!ReportName
That's it.
I have ckeditor in the application in asp.net application through jquery.
It's working fine at local. Its inserting data in database, does not matter
whatever is the length of the text. But when I insert data on live after
putting the build on the server.
It is not saving the data, when I reduce, its length then it is saving the data.I am inserting this text using WCF service.
Please help in this context.
Looking forward to hear regarding the same.
Oracle DB accepts 4000 characters as a max length of an input string (NOT a datatype).
i.e, you are expected to send at most 4000 chars as a value.
The solution:
if you are using ASP.NET, try to use this function after changing your column type to CLOB so that its size would be up to 4GB:
Public Shared Function AssignStringToCLOB(ByVal targetString As String, ByVal myConnection As OracleConnection) As OracleLob
Dim _tempCommand As New OracleCommand()
_tempCommand.Connection = myConnection
_tempCommand.Transaction = _tempCommand.Connection.BeginTransaction()
_tempCommand.CommandText = "DECLARE A " + OracleType.Clob.ToString() + "; " + "BEGIN " + "DBMS_LOB.CREATETEMPORARY(A, FALSE); " + ":LOC := A; " + "END;"
Dim p As OracleParameter = _tempCommand.Parameters.Add("LOC", OracleType.Clob)
p.Direction = ParameterDirection.Output
_tempCommand.ExecuteNonQuery()
Dim _tempCLOB As OracleLob = CType(p.Value, OracleLob)
If targetString <> String.Empty Then
Dim _bytesArray As Byte() = Text.Encoding.Unicode.GetBytes(targetString)
_tempCLOB.BeginBatch(OracleLobOpenMode.ReadWrite)
_tempCLOB.Write(_bytesArray, 0, _bytesArray.Length)
_tempCLOB.EndBatch()
End If
_tempCommand.Transaction.Commit()
Return _tempCLOB
End Function
and call it after opening the connection with Oracle DB to set a value to your parameter, this should work perfectly.
I am trying to use the ADO to read in a series of text files into a worksheet. I am running into problems when the majority of the data in a specific column are integers. It will give null values (blank cells) when it reaches a String.
According to microsoft support (Ado mixed data tyes) this is a common thing and the solution is to set the IMEX = 1. I tried this however it didn't work.
I have been searching others threads looking for the answer and came across this answer (other thread) where the author says to change TypeGuessRows to "get the Jet to detect whether a mixed types situation exists and trick the Jet into detecting a certain data type." However, this hasn't worked either.
Below is my VBA code. Any help would be appreciated
Sub query_text_file(WorkingSheet As String, Col As String, Row As Integer, fileName As String, firstOrLast As Integer)
Dim strPath As String
Dim ws As Worksheet
strToolWkbk = fileName
strPath = ThisWorkbook.Path & "\Excel_Barcode_Files"
Set ws = Worksheets(WorkingSheet)
'Need to reference the:
' Microsoft ActiveX Data Objects 2.5 Library
Dim s_rst As ADODB.Recordset
Dim s_cnn As ADODB.Connection 's for sub connection
Dim intRow As Integer
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Set s_cnn = New ADODB.Connection
s_cnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";" _
& "Extended Properties=""text;HDR=Yes;IMEX=1;TypeGuessRows=12;FMT=Delimited"";"
s_cnn.Open
Set s_rst = New ADODB.Recordset
strSQL = "SELECT * FROM " & strToolWkbk
s_rst.Open strSQL, _
s_cnn, adOpenStatic, adLockOptimistic, adCmdText
intRow = Row
s_rst.MoveFirst
Do Until s_rst.EOF
ws.Range(Col & intRow) = s_rst(0)
ws.Range(Chr(Asc(Col) + 1) & intRow) = s_rst(1)
intRow = intRow + 1
s_rst.MoveNext
Loop
s_rst.Close
s_cnn.Close
Set s_rst = Nothing
Set s_cnn = Nothing
End Sub
Here is a sample text file. The code reads in everything except the "P"
test test
P,0
1,1
5,2
6,3
Basically, don't rely on the registry entries as explained here on MSDN.
You need to create a Schema.ini file and put it in the same folder as all your text files. In the Schema.ini you specify the type for all columns you may have in your text files - it's just a much safer option to do that explicitly rather than have the driver work out the correct types for columns...
Say you have some txt files on your desktop, open Notepad and copy paste the below - make sure you adjust the [test.txt] part to match the name of your actual txt file and save it as: Schema.ini
[test.txt]
Format=CSVDelimited
Col1=Column1 Text
Col2=Column2 Text
Make sure you add another slash at the end of the parth in the strPath (also indicated in the article)
strPath = ThisWorkbook.Path & "\Excel_Barcode_Files\"
*Keep in mind that I am working in a different location to yours - I am using my Desktop for this example and my text file is named test.txt
Now, that you have a Schema.ini you can modify the connection string and take out some parameters which are not required because they exists in the Schema.ini
So bascially an SSCCE based on the above assumptions would be:
Sub Main()
Cells.ClearContents
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim thePath As String
thePath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & thePath & ";" _
& "Extended Properties=""text;HDR=No;"""
cn.Open
Dim sql As String
sql = "SELECT * FROM test.txt"
' populate the recordset
rs.Open sql, cn, adOpenStatic, adLockOptimistic, &H1
' copy the recordset starting at Range("A1") - assuming there are no headers - see HDR = No;
Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Now after running this you should see all the values including the missing P:
My C# Console Applcation:
1:
string CE_ParentName_ = CEReader5[0].ToString(); // get string with lithuanian letters for example "Konsolės".
if I use Console.WriteLine() , I get correct output in console.
2:
readname.CommandText = "SELECT [ID] FROM [Net7].[dbo].[GroupFilter] WHERE
[GroupFilterName]='" + CE_ParentName_ + "'"; // I need to find records in my DB with name of that string (1 possible option)
3:
if (NameReader.Read()) { idd = NameReader[0].ToString(); } // if i get any results ar no.2 i need to read them
The point is that no.2 returns zero results if string contains lithuanian letters. If string is w/o lithuanian letters - everything works perfect. Tried everything, you are my last hope folks.
Are Lithuanian characters multibyte? (like Japanese for example)
Is the GroupFilterName NVARCHAR or VARCHAR? If it's NVARCHAR, perhaps you need to put N in front of the string.
Eg.
readname.CommandText = "SELECT [ID] FROM [Net7].[dbo].[GroupFilter] WHERE
[GroupFilterName]=N'" + CE_ParentName_ + "'";
And see asawyer's comment regarding avoiding injection attacks.
I have a c# function that needs to write to a SQL image column. I have the image in a byte array. The standard seems to be the use of SqlCommand while passing the byte array as a parameter of type System.Data.SqlDbType.Image.
Unfotunately, my function can only use text queries (don't ask why) so I have to find a way to use T-SQL commands only. What I have so far can write to the column but I don't know what format of string to make the image blob string.
sql = "DECLARE #ptrval binary(16)" +
"SELECT #ptrval = textptr(Photo) FROM EMPhoto WHERE Employee='" + employeeID + "'" +
"WRITETEXT EMPhoto.Photo #ptrval " + imageByteArrayAsString;
I've tried converting imageByteArray to a Hex string and Binary string but it doesn't seem to end up correct in SQL or in the application that reads it.
A T-SQL Binary constant is an unquoted hexidecimal string prefixed with 0x. ie 0xFFD8FFE0...
string imageByteArrayAsString = "0x" + BitConverter.ToString(image).Replace("-", string.Empty);