向SQL Server表插入对象列表

时间:2018-07-23 13:50:52

标签: c# .net sql-server ado.net

想要将对象列表插入sql server表。 我只是想知道是否有一种方法可以一次将所有对象插入记录列表中?

public int stockInsert()
{
       int result = 0;

       string queryStr = "insert into Stock(stockID,color_Available,size_Available,qty_Available,detail_Img,productId)"
       + "values(@stockID,@color_Available,@size_Available,@qty_Available,@detail_Img,@productId)";

       con.Open();
       SqlCommand cmd = new SqlCommand(queryStr, con);

       cmd.Parameters.AddWithValue("@stockID", this.StockID);
       cmd.Parameters.AddWithValue("@color_Available", this.ColorAvailable);
       cmd.Parameters.AddWithValue("@size_Available", this.SizeAvailable);
       cmd.Parameters.AddWithValue("@qty_Available", this.QtyAvailable);
       cmd.Parameters.AddWithValue("@detail_Img", this.DetailImg);
       cmd.Parameters.AddWithValue("@productId", this.ProductID);

       result += cmd.ExecuteNonQuery();
       con.Close();

       return result;
   }

1 个答案:

答案 0 :(得分:0)

试一下,然后反馈。您正在将数据从文本文件加载到DataTable中,然后从那里将数据推送到SQL Server DB中。

private void Button1_Click(object sender, System.EventArgs e) {
        DataTable tblReadCSV = new DataTable();
        tblReadCSV.Columns.Add("FName");
        tblReadCSV.Columns.Add("LName");
        tblReadCSV.Columns.Add("Department");
        TextFieldParser csvParser = new TextFieldParser("C:\\your_path_here\\Employee.txt");
        csvParser.Delimiters = new string[] {
                ","};
        csvParser.TrimWhiteSpace = true;
        csvParser.ReadLine();
        while (!(csvParser.EndOfData == true)) {
            tblReadCSV.Rows.Add(csvParser.ReadFields());
        }

        SqlConnection con = new SqlConnection("Server=your_server_name;Database=your_DB_name;Trusted_Connection=True;");
        string strSql = "Insert into Employee(FName,LName,Department) values(@Fname,@Lname,@Department)";
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strSql;
        cmd.Connection = con;
        cmd.Parameters.Add("@Fname", SqlDbType.VarChar, 50, "FName");
        cmd.Parameters.Add("@Lname", SqlDbType.VarChar, 50, "LName");
        cmd.Parameters.Add("@Department", SqlDbType.VarChar, 50, "Department");
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.InsertCommand = cmd;
        int result = dAdapter.Update(tblReadCSV);
    }