把csv文件导入数据库
protected void Page_Load(object sender, EventArgs e) { string paths = Server.MapPath(""); DataSet ds3= getcsv(paths, paths+"2010年淘趣后台导入价格表样式20100828.csv"); GridView1.DataSource = ds3; GridView1.DataBind(); } private DataSet getcsv(string filepath, string filename) { string strconn = @"driver={microsoft text driver (*.txt; *.csv)};dbq="; strconn += filepath; strconn += ";extensions=asc,csv,tab,txt;"; System.Data.Odbc.OdbcConnection con = new OdbcConnection(strconn); DataSet data = new DataSet(); string sql = "select 材质,品牌 from " + filename; OdbcDataAdapter adp = new OdbcDataAdapter(sql, con); // con.open(); adp.Fill(data); return data; }
///
/// 将csv格式文件导成dataset
///
///文件路径
///文件名
///
private dataset getcsv(string filepath,string filename)
{
string strconn = @"driver={microsoft text driver (*.txt; *.csv)};dbq=";
strconn += filepath;
strconn += ";extensions=asc,csv,tab,txt;";
odbcconnection con = new odbcconnection(strconn);
dataset data = new dataset();
string sql = "select * from " + filename;
odbcdataadapter adp = new odbcdataadapter(sql, con);
// con.open();
adp.fill(data);
return data;
}
///
/// 把dataset数据插入数据库
///
///
///表名
///
public bool bulkdata(dataset _ds, string _tablename)
{
string strconn = "server=.;database=filessync;uid=sa;pwd=123";
sqlconnection sqlcon = new sqlconnection(strconn);
sqlcon.open();
sqlbulkcopy sqlbulk = new sqlbulkcopy(sqlcon);
sqlbulk.destinationtablename = _tablename;
try
{
sqlbulk.writetoserver(_ds.tables[0],datarowstate.unchanged);
return true;
}
catch
{
return false;
}
finally
{
sqlcon.close();
sqlcon.dispose();
sqlbulk.close();
}
}
dataset ds = getcsv("e:\\", "yx.csv");
gridview1.datasource = ds.tables[0].defaultview;
gridview1.databind();
bool isbool = bulkdata(ds, "td_data");
if (isbool)
{
response.write("
");
}
else
{
response.write("
");
}
把csv文件导成dataset成功,但是把dataset的内容导入数据怎么失败
sqlbulk.writetoserver(_ds.tables[0],datarowstate.unchanged);这句报错
无法访问目标表 tb_data
好像把那个gridview绑定去了就可以了