
(BLOB)
作为二进制或字符数据写入数据库,具体视数据源的字段类型而定。若要将
BLOB
值写入数据库,请发出相应的
INSERT
或
UPDATE
语句并将
BLOB
值作为输入参数传递(请参见将存储过程用于命令)。如果
BLOB
存储为文本格式(如
SQL
Server
text
字段),则可将
BLOB
作为字符串参数传递。如果
BLOB
存储为二进制格式(如
SQL
Server
image
字段),则可将类型
byte
的数组作为二进制参数传递。
注意
BLOB
可能相当大,因此在作为单个值写入时可能要使用大量的系统内存,从而降低应用程序的性能。若要减少写入
BLOB
值时所使用的内存量,可以按“块”将
BLOB
写入数据库。用该方法将
BLOB
写入数据库的过程具体取决于数据源的功能。有关按块将
BLOB
值写入
SQL
Server
的示例,请参见将
BLOB
值写入
SQL
Server
时节省资源。
以下代码示例将员工信息添加到
Northwind
数据库的
Employees
表中。员工照片将从文件中读取并添加到表中的
Photo
字段,该字段为
image
字段。
public
static
void
AddEmployee(
string
lastName,
string
firstName,
string
title,
DateTime
hireDate,
int
reportsTo,
string
photoFilePath,
string
connectionString){
byte[]
photo
=
GetPhoto(photoFilePath)
using
(SqlConnection
connection
=
new
SqlConnection(
connectionString))
SqlCommand
command
=
new
SqlCommand(
"INSERT
INTO
Employees
(LastName,
FirstName,
"
+
"Title,
HireDate,
ReportsTo,
Photo)
"
+
"Values(@LastName,
@FirstName,
@Title,
"
+
"@HireDate,
@ReportsTo,
@Photo)",
connection)
command.Parameters.Add("@LastName",
SqlDbType.NVarChar,
20).Value
=
lastName
command.Parameters.Add("@FirstName",
SqlDbType.NVarChar,
10).Value
=
firstName
command.Parameters.Add("@Title",
SqlDbType.NVarChar,
30).Value
=
title
command.Parameters.Add("@HireDate",
SqlDbType.DateTime).Value
=
hireDate
command.Parameters.Add("@ReportsTo",
SqlDbType.Int).Value
=
reportsTo
command.Parameters.Add("@Photo",
SqlDbType.Image,
photo.Length).Value
=
photo
connection.Open()
command.ExecuteNonQuery()
}}public
static
byte[]
GetPhoto(string
filePath){
FileStream
stream
=
new
FileStream(
filePath,
FileMode.Open,
FileAccess.Read)
BinaryReader
reader
=
new
BinaryReader(stream)
byte[]
photo
=
reader.ReadBytes((int)stream.Length)
reader.Close()
stream.Close()
return
photo}
insert into table select * from temp_table
这个语法中,insert 和 select 都写清楚列名:
insert into table(col1,col2,...) select col1,col2,... from temp_table欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)