读取.csv文件,存储在SQL数据库中
本文关键字:SQL 数据库 存储 csv 文件 读取 | 更新日期: 2023-09-27 18:37:04
对于编程分配,我要编写一个原型。现在我只在寻找代码 1 方法。该方法应该读取区域设置.csv文件,并将其另存为 BLOB(二进制大对象)保存在外部服务器上的数据库中。但是,我对 C# 很陌生,我已经习惯了 Java。我不太确定 BLOB 是什么,某种字节数组或其他东西?
到目前为止,我的程序可以
- 连接到 SQL 服务器。
- 读取.csv文件。
数据库表称为 tblUsers。
我尝试将其插入的字段是 BlobFile,其数据类型为 varbinary(8000)。
我什至不知道数据类型是否正确。
我想要的只是保存在服务器上的表中的.csv文件。
"字符串或二进制数据将被截断。该声明已终止。不幸的是,我得到的是,我可以弄清楚这意味着我的.csv文件与我在表中的数据类型有些不匹配。我不知道如何将您链接到.csv,但它看起来像:
4.012 3.012 1.312 3.321 4.232
等等。这是 C# 代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string filePath = "C:/Users/Soeren/Desktop/epilepsi - semester/EpilepsiEKG/Patient1_Reciprocal_HFpower_x1.csv";
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
string line = fs.ReadLine();
string[] value = line.Split(',');
BinaryReader reader = new BinaryReader(fs);
byte[] BlobValue = reader.ReadBytes((int)fs.Length);
fs.Close();
reader.Close();
//FILE READ!
SqlConnection con = new SqlConnection(@"Data Source=webhotel10.iha.dk;Initial Catalog=F13ST2ITS2201270867;Persist Security Info=True;User ID=F13ST2ITS2201270867;Password=F13ST2ITS2201270867");
SqlCommand com = new SqlCommand("insert into tblUsers(BlobFilename,BlobFile) values(@BlobFilename,@Blobfile)", con);
SqlParameter BlobFileNameParam = new SqlParameter("@BlobFileName", SqlDbType.NChar);
SqlParameter BlobFileParam = new SqlParameter("@BlobFile", SqlDbType.Binary);
com.Parameters.Add(BlobFileNameParam);
com.Parameters.Add(BlobFileParam);
BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("/") + 1);
BlobFileParam.Value = BlobValue;
try
{
com.Connection.Open();
com.ExecuteNonQuery();
MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.", "BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
com.Connection.Close();
}
}
}
}
BlobFileParam 参数的声明方式是,它是一个大小为 0 的固定长度二进制参数(因为未指定大小)。您尝试插入长度大于指定大小 (0) 的数据。尝试将参数 BlobFileParam 的大小属性设置为正确的长度;我也认为SqlDbType.VarBinary可能是参数类型的更好选择。