在将文件保存到SQL数据库中时出错
问题描述:
我已经在SQl中创建了一个表.
桌子是这样的..
I have created a table in SQl.
The table is like this..
Create table filee
(
id varchar(5),
filee nvarchar(max)
)
之后,我要在(filee)列中保存一个(.doc)文件.
我已经编写了一个代码,但是此代码给出了错误.
代码是这样的.....
After that I want to save a (.doc) file in filee column.
I have written a code but this code give error.
The code is like this.....
FileStream fs = new FileStream(flname, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Mith;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("Select * from filee",con);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds, "filee");
DataRow dr = ds.Tables["filee"].NewRow();
dr[0] = textBox1.Text;
dr[1] = data;
try
{
ds.Tables["filee"].Rows.Add(dr);
da.Update(ds, "filee");
MessageBox.Show("Data Inserted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.close()
}
答
HI,
在上面的代码中,您无处创建任何文件,也无处读取任何文件.
解决方法如下:
In the above code nowhere ur creating any file, and from nowhere ur reading any file.
Here is the solution :
protected void btnCreate_Click(object sender, EventArgs e)
{
FileStream createFile = new FileStream(@"C:\Docs\file2.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
createFile.Close();
StreamWriter sw = new StreamWriter(@"C:\Docs\file2.docx");
sw.Write("Tajuddin............");
sw.Close();
StreamReader sr=new StreamReader (@"c:\docs\file2.docx");
string fileData=sr.ReadToEnd ();
sr.Close();
//after this u can write insert query to store in file column
string sqlquery = string.Format("insert into filee values('{0}','{1}')", "123", fileData);
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Mith;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(sqlquery, con);
cmd.ExecuteNonQuery();
}
使数据类型文本代替nvarchar(max)
make your datatype text in place of nvarchar(max)