HomeDatabaseMysql TutorialMS-SQL Server 中单引号的两种处理方法

MS-SQL Server 中单引号的两种处理方法

和数据库打交道要频繁地用到 SQL 语句,除非你是全部用控件绑定的方式,但采用控件绑定的方式存在着灵活性差、效率低、功能弱等等缺点。因此,大多数的程序员极少或较少用这种绑定的方式。而采用非绑定方式时许多程序员大都忽略了对单引号的特殊处理,一旦SQL语句的查询条件的变量有单引号出现,数据库引擎就会报错指出SQL语法不对,本人发现有两种方法可以解决和处理这种单引号的问题(以VB为例子)。

---- 方法一:利用转义字符处理SQL语句。下面的函数可以在执行SQL语句前调用,执行处理后的结果即可产生正确的结果。

代码如下:Function ProcessStr(str As String)
Dim pos As Integer
Dim stedest As String
pos = InStr(str, “'“)

While pos 〉0
str = Mid(str, 1, pos) & “'“ & Mid(str, pos + 1)
pos = InStr(pos + 2, str, “'“)
Wend
ProcessStr = str
End Function

---- 其中str参数是你的SQL字符串。函数一旦发现字符串中有单引号出现,就在前面补上一个单引号。
---- 方法二:利用数据对象中的参数。可以利用ADODB.COMMAND对象,把含有单引号的字符串传递给COMMAND,然后执行查询等操作即可。

---- 以上两种方法比较,方法一增加了系统处理时间,方法二简洁、高效,如果采用存储过程,然后再传递参数给存储过程,存储过程是预编译的,这样系统的效率更高。

---- 下面就举例子加以说明。

---- 新建一个项目,项目中有一个窗体(Form1),两个命令按钮,一个MSFlexGrid,名称分别为:Command1,Command2,MSFlexGrid1,一个COMBOX(COMBO1),它的内容预先设定为“Paolo''f“、“Paolo'f“。Command1演示方法一,Command2演示方法二,MSFlexGrid1存储方法二查询(SELECT)结果。对于其他的SQL操作(INSERT、DELTER、UPDATAE)方法极为类似,笔者就不再赘述。例子中用到SQL SERVER中的PUBS数据库中的EMPLOYEE表,同时可以用SQL语法把其中两条记录中的FNAME改为“Paolo''f“、“Paolo'f“。 SQL语法如下:

update employee set fname=“ Paolo''''f“
where emp_id='PMA42628M'
update employee set fname=“ Paolo''f“
where emp_id='PMA42628M'

---- 程序如下:
---- 首先把前面的函数加入。

---- 在窗体的通用中声明如下变量:

Dim cnn1 As ADODB.Connection '连接
Dim mycommand As ADODB.Command '命令
Dim rstByQuery As ADODB.Recordset '结果集
Dim strCnn As String '连接字符串
Private Sub Form_Load()
Set cnn1 = New ADODB.Connection '生成一个连接
strCnn = “driver={SQL Server};“ & _
“server=ZYX_pc;uid=sa;pwd=PCDC;database=pubs“ '
没有系统数据源使用连接字符串

'strCnn = “DSN=mydsn;UID=sa;PWD=;“
'DATABASE=pubs;Driver={SQL Server};SERVER=gzl_pc“ '
如果系统数据源MYDSN指向PUBS数据库,也可以这样用
cnn1.Open strCnn, , , 0 '打开连接
End Sub
Private Sub Command1_Click() '演示字符处理
Dim i As Integer
Dim j As Integer
Set parm = New ADODB.Parameter
Set mycommand = New ADODB.Command

Dim str As String
str = Combo1.Text
str = ProcessStr (str)
mycommand.ActiveConnection = cnn1 '
指定该command 的当前活动连接
mycommand.CommandText = “ select * from
employee where fname = '“ & str & “'“
mycommand.CommandType = adCmdText '表明command 类型
Set rstByQuery = New ADODB.Recordset
Set rstByQuery = mycommand.Execute()
i = 0
Do While Not rstByQuery.EOF
i = i + 1 ' i 中保存记录个数
rstByQuery.MoveNext
Loop
MSFlexGrid1.Rows = i + 1 '动态设置MSFlexGrid的行和列
MSFlexGrid1.Cols = rstByQuery.Fields.count + 1
MSFlexGrid1.Row = 0
For i = 0 To rstByQuery.Fields.count - 1
MSFlexGrid1.Col = i + 1
MSFlexGrid1.Text = rstByQuery.Fields.Item(i).Name
Next '设置第一行的标题,用域名填充

i = 0
'Set rstByQuery = mycommand.Execute()
rstByQuery.Requery
Do While Not rstByQuery.EOF
i = i + 1
MSFlexGrid1.Row = i '确定行
For j = 0 To rstByQuery.Fields.count - 1
MSFlexGrid1.Col = j + 1
MSFlexGrid1.Text = rstByQuery(j) '添充所有的列
Next
rstByQuery.MoveNext

Loop '这个循环用来填充MSFlexGrid的内容
End Sub
Private Sub Command2_Click()'参数方法
Dim i As Integer
Dim j As Integer

Set parm = New ADODB.Parameter
Set mycommand = New ADODB.Command

' parm_jobid.Name = “name1“ this line can be ommited
parm.Type = adChar '参数类型
parm.Size = 10 '参数长度
parm.Direction = adParamInput '参数方向,输入或输出
parm.Value = Combo1.Text '参数的值
mycommand.Parameters.Append parm '加入参数
mycommand.ActiveConnection = cnn1 '
指定该command 的当前活动连接
mycommand.CommandText = “ select *
from employee where fname =? “
mycommand.CommandType = adCmdText '表明command 类型
Set rstByQuery = New ADODB.Recordset
Set rstByQuery = mycommand.Execute()
i = 0
Do While Not rstByQuery.EOF
i = i + 1 ' i 中保存记录个数
rstByQuery.MoveNext
Loop
MSFlexGrid1.Rows = i + 1 '动态设置MSFlexGrid的行和列
MSFlexGrid1.Cols = rstByQuery.Fields.count + 1
MSFlexGrid1.Row = 0
For i = 0 To rstByQuery.Fields.count - 1
MSFlexGrid1.Col = i + 1
MSFlexGrid1.Text = rstByQuery.Fields.Item(i).Name
Next '设置第一行的标题,用域名填充

i = 0
rstByQuery.Requery
Do While Not rstByQuery.EOF
i = i + 1
MSFlexGrid1.Row = i '确定行
For j = 0 To rstByQuery.Fields.count - 1
MSFlexGrid1.Col = j + 1
MSFlexGrid1.Text = rstByQuery(j) '添充所有的列
Next
rstByQuery.MoveNext

Loop '这个循环用来填充MSFlexGrid的内容
End Sub

---- 查询部分可以用存储过程以提高处理效率,减低网络流量。
---- 本程序在NT WORKSTATION 4.0 SP4、SQL SERVER 7.0 上调试通过
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor