由於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 =@"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();