首页 > 开发 > 综合 > 正文

C#向Sql Server中插入记录时单引号的处理

2024-07-21 02:18:42
字体:
来源:转载
供稿:网友
asp.net种使用c#, 向coredb.mybbs表中插入记录值(title, content)【文章的标题和内容】,由于content, title中可能包含单引号,直接使用sql的insert命令会报错,对此有两种处理方法,一种将单引号替换成两个单引号,第2种方法是使用存储过程。

表mybbs的格式定义如下:
create table [dbo].[mybbs] (
[id] [bigint] identity (1, 1) not null ,
[title] [char] (160) collate chinese_prc_ci_as null ,
[author] [char] (20) collate chinese_prc_ci_as null ,
[date_of_created] [datetime] null ,
[abstract] [char] (480) collate chinese_prc_ci_as null ,
[content] [ntext] collate chinese_prc_ci_as not null
) on [primary] textimage_on [primary]

1、将单引号用两个单引号替换:
sqlconnection coredb=new sqlconnection();
coredb.connectionstring= "workstation id=/"gqa-eric-lv/";packet size=4096;integrated security=sspi;" +
"data source=/"gqa-eric-lv/";persist security info=false;initial catalog=coredb";

//单引号用"''"替换,以插入'到sql server中;
string title=textbox1.text.replace("'","''");
string content=textbox2.text.replace("'","''");
if(title.trim()==""||content.trim()=="")return;
string insertcmd [email protected]"insert into mybbs (title,content) values('"+ title + "','" +content+"')";

sqlcommand mycommand = new sqlcommand(insertcmd,coredb);
coredb.open();
sqldatareader myreader = mycommand.executereader();
myreader.close();
coredb.close();

2、使用存储过程来插入

1) 创建存储过程:
create proc insertmybbsproc(@title char(160), @author char(20), @content ntext)
as
insert into mybbs(title,author,content) values(@title, @author, @content)

2) 查询分析器中测试存储过程:
declare @title char(160)
declare @author char(20)
declare @content char(600)
set @title='test title 3'
set @author='david euler 3'
set @content='it is the content 3'
exec insertmybbsproc @title, @author, @content

3) c#中通过sqlcommand执行存储过程:
sqlconnection coredb=new sqlconnection();
coredb.connectionstring= "workstation id=/"gqa-eric-lv/";packet size=4096;integrated security=sspi;" +
"data source=/"gqa-eric-lv/";persist security info=false;initial catalog=coredb";

string title=textbox1.text;
string content=textbox2.text;

if(title.trim()==""||content.trim()=="")return;

//insertmybbsproc是向mybbs中插入数据的procedure:
sqlcommand insertcmd = new sqlcommand("insertmybbsproc",coredb);

insertcmd.commandtype=commandtype.storedprocedure;//命令类型为存储过程;下面定义参数对象:
sqlparameter prm1=new sqlparameter("@title", sqldbtype.char,160);
sqlparameter prm2=new sqlparameter("@author", sqldbtype.char,20);
sqlparameter prm3=new sqlparameter("@content",sqldbtype.ntext,1073741823);
prm1.direction=parameterdirection.input;
prm2.direction=parameterdirection.input;
prm3.direction=parameterdirection.input;
//为insertcmd添加sql参数:
insertcmd.parameters.add(prm1);
insertcmd.parameters.add(prm2);
insertcmd.parameters.add(prm3);
//为sql参数赋值:
prm1.value=title;
prm2.value="david euler";
prm3.value=content;

coredb.open();
int recordsaffected=insertcmd.executenonquery();
if(recordsaffected==1)response.write("<script>alert('"+ "插入成功" +"');</script>");
coredb.close();


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表