Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use c # to access SQL data

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to use c # to access SQL data". In daily operation, I believe many people have doubts about how to use c # to access SQL data. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to access SQL data using c #". Next, please follow the editor to study!

How to create a database that can use FileStream

1. Create a database

The following T-SQL statements can be executed when creating data

CREATEDATABASETestDBONPRIMARY (NAME=TestDB,FILENAME='c:\ data\ TestDB.mdf'), FILEGROUPFileStreamGroup1CONTAINSFILESTREAM (NAME=Arch4,FILENAME='c:\ data\ filestream1') LOGON (NAME=TestDBlog,FILENAME='c:\ data\ TestDBlog.ldf') GO

If you enable FileStream on a database that has already been created, you can

A.Rightclickthe "TestDB" databaseandselect "Properties" .b.FirstcreateaFileGroup, click "Filegroups" menuandcreateoneunder "Stream" section,named "FileStreamGroup1" .Andthenclick "Files" menu,andaddafilenamed "filestream1" andSetit'sFileGroupto "FileStreamGroup1", andthenspecifyafoldertoholddata,likec:\ Data.Clickok,andyoucancheckthefolder "c:\ data" toseewhatisadded.

two。 Create a tabl

[ID] [uniqueidentifier] ROWGUIDCOLNOTNULL, [ContentType] [nvarchar] (50) NOTNULL, [FileName] [nvarchar] (50) NOTNULL, [FileContent] [varbinary] (max) FILESTREAMNULL, [FileSize] [int] NULL, CONSTRAINT [TestTable2 _ TestTable2] PRIMARYKEYCLUSTERED ([ID] ASC) WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON) on [fileStreamGroup1]) on [prime] FILESTREAM_ on [FileStreamGroup1] GOSETANSI_PADDINGOFFGO

If the table has been created, you can execute the following TSQL to set it:

[TestTable] altered columnID [uniqueidentifier] notnullALTERTABLE.[ TestTable] altercolumnIDaddROWGUIDCOLALTERTABLE.TestTable addFileContentvarbinary (MAX) FILESTREAM

How to use c # to access SQL data

Read:

SqlConnectionconn=null;conn=newSqlConnection (connect); conn.Open (); tx=conn.BeginTransaction (); varqry= "SELECTFileName,FileContent.PathName () asFilePath,ContentType,GET_FILESTREAM_TRANSACTION_CONTEXT () asTranContextFROMTestTable2WHEREID=@ID"; varcmd=newSqlCommand (qry,conn,tx); cmd.Parameters.AddWithValue ("@ ID", id); using (rdr=cmd.ExecuteReader ()) {if (rdr.HasRows) {rdr.Read (); fileModel=newFileModel (); fileModel.FileName=Convert.ToString (rdr ["FileName"]); fileModel.FilePath=Convert.ToString (rdr ["FilePath"]) Byte [] tranContext= (byte []) rdr ["TranContext"]; fileModel.ContentType=Convert.ToString (rdr ["ContentType"]);; fileModel.FileStream=newSqlFileStream (fileModel.FilePath,tranContext,FileAccess.Read);}}

With the Stream of the file, you can read and write to the file.

Write:

PublicstaticvoidPostFileToDB (HttpPostedFileBasefile) {stringfileName=Path.GetFileName (file.FileName); stringcontentType=file.ContentType;intfilefileSize=file.ContentLength/1024;using (SqlConnectionconn=newSqlConnection (connect)) {conn.Open (); using (SqlTransactiontrn=conn.BeginTransaction ()) {SqlCommandcmdInsert=newSqlCommand (@ "insertintoTestTable2 (FileName,FileContent,ContentType,FileSize) outputINSERTED.FileContent.PathName (), GET_FILESTREAM_TRANSACTION_CONTEXT () values (@ FileName,0x,@ContentType,@FileSize)", conn,trn); cmdInsert.Parameters.Add ("@ FileName", SqlDbType.VarChar,256); cmdInsert.Parameters ["@ FileName"] .Value=fileName CmdInsert.Parameters.Add ("@ ContentType", SqlDbType.VarChar,256); cmdInsert.Parameters ["@ ContentType"] .value = contentType;cmdInsert.Parameters.Add ("@ FileSize", SqlDbType.Int); cmdInsert.Parameters ["@ FileSize"] .value = fileSize;stringpath=null;byte [] context=null;//cmdInsertisanINSERTcommandthatusestheOUTPUTclause//ThusweusetheExecuteReadertogetthe//resultsetfromtheoutputcolumns//using (SqlDataReaderrdr=cmdInsert.ExecuteReader ()) {rdr.Read (); path=rdr.GetString (0); context=rdr.GetSqlBytes (1) .Buffer;} using (SqlFileStreamsfs=newSqlFileStream (path,context,FileAccess.Write)) {file.InputStream.CopyTo (sfs) } trn.Commit ();}

At this point, the study on "how to access SQL data using c #" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report