SQL执行含有中文字符的查询时有问题,结果为空,求解
vb2012连接sql server数据库文件,数据表名称为Data,有以下几条记录:
ID Title_CH Title_EN
10 白宫陷落 Olympus Has Fallen
9 钢铁侠III Iron Man 3
查询语句是这样的:
Public Class frmQuery
Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim strSQLCommand As String
Dim strQuerySQLCommand As String
Private Sub btnQuery_Click(sender As Object, e As EventArgs) Handles btnQuery.Click
'数据库连接
cn = New SqlConnection
cn.ConnectionString = "Server=(localdb)\v11.0;AttachDbFilename=|DataDirectory|DATABASE.mdf;Trusted_Connection=Yes"
'SQL查询语句
strQuerySQLCommand = "SELECT Data.ID AS 编号, Title_EN AS 外文名称, Title_CH AS 中文名称"
strQuerySQLCommand += " FROM Data WHERE Data.ID=Data.ID"
If chkTitle_EN.Checked = True Then
strQuerySQLCommand += " AND Data.Title_EN LIKE '%" & txtSearchTitle_EN.Text & "%'"
End If
If chkTitle_CH.Checked = True Then
strQuerySQLCommand += " AND Data.Title_CH LIKE '%" & txtSearchTitle_CH.Text & "%'"
End If
Try
cn.Open()
Dim cd As New SqlCommand(strQuerySQLCommand, cn)
Dim drd As SqlDataReader
drd = cd.ExecuteReader()
Dim dt As DataTable = New DataTable
dt.Load(drd)
'DataGridView填充
dgvResult.DataSource = dt
cn.Close()
Catch
MsgBox("查询出错", vbCritical, "警告")
End Try
End Sub
又:你的字符串没加 N 前缀,我就认为字段是 Varchar 的。其实是你的 SQL 和字段类型不匹配。
又:你的客户端和数据库的语言不一致吧,否则就算转 Ansi 也是一致的。