C # Processing of single quotes when inserting records in SQL Server

xiaoxiao2021-03-06  50

Author: David Eulerdate: 2004/11 / 17email: DE_EULER-David@yahoo.com If you have any questions, please contact me :) ASP.NET species using C #, inserts recorded values ​​to the Coredb.mybbs table (Title, Content ) [Title and content of the article] Since the content, Title may contain single quotes, use SQL INSERT commands will report an error, there are two processing methods, one will replace single quotes into two single quotes, second The method is to use the stored procedure.

Table Mybbs is defined as follows: 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, Replacing single quotes with two single quotes: sqlConnection core (); Coredb.connectionstring = "Workstation ID = /" gqa-eric-lv / "; packet size = 4096; integrated security = sspi;" "DATA Source = / "gqa-eric-lv /"; init security info = false; initial catalog = coredb "; // single quotation with" '' "replacing to insert 'into SQL Server; string title = textbox1.text. Replace ("'", "' '"); string content = textbox2.text.replace ("'", "''); if (title.trim () ==" "|| Content.trim () = = "" "Return; String INSERTCMD = @" 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, using stored procedures 1) Create a stored procedure: Create Proc insertmybbsproc (@title char (160), @Author char (20) , @Content Ntext) AS INSERT INTO Mybbs (Title, Author, Content) Values ​​(@title, @Author, @content) 2) Query Analyzer Test stored procedure: declare @Title Char (160) Declare @Author char (20 ) DECLARE @Content Char (600) Set @ title = 'Test title 3'set @ Author ='

转载请注明原文地址:https://www.9cbs.com/read-89577.html

New Post(0)