1

我需要阅读关于如何将 DevExpress 中的 gridView 导出到 SQL 表的小课程。就像值 First Name、Father Name、Last Name 到表 Employee 一样,我有很多行。如何循环到每一行并将数据发送到数据库..

提前谢谢

我试过这段代码:

string sql = @"INSERT INTO Emp (@FName, @MName,@LName, @Code, @TaxNb, @SSN, @EmploymentType, @DOB, @MarStat, @RegNum, @BadgeNum, @HireDate, @TaxSince, @HireSince, @ArEmpName, @ArFatherName, @ArLastName, ArPayUnit)";

DataTable table = new DataTable();
try
{
    SqlConnection connection = new SqlConnection(@"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2");

    SqlCommand command = new SqlCommand(sql, connection);
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.InsertCommand = command;
    connection.Open();
    // for (int i =0; i< gridView3.RowCount; i++)
    //{
    //command.Parameters.Add(@FirstName, gridView3.GetRowCellValue(i,gridView3.Columns));
    //adapter.InsertCommand.ExecuteNonQuery();
    //}

    SqlParameter[] MyParams = new SqlParameter[28];

    MyParams[0] = new SqlParameter("@FName", SqlDbType.VarChar, 20);
    MyParams[0].SourceColumn = FirstName;
    command.Parameters.Add("@FName", SqlDbType.VarChar, 20);

    MyParams[1] = new SqlParameter("@MName", SqlDbType.VarChar, 20);
    MyParams[1].SourceColumn = FatherName;

    MyParams[2] = new SqlParameter("@LName", SqlDbType.VarChar, 20);
    MyParams[2].SourceColumn = LastName;
4

1 回答 1

1

SqlDataAdapter 类

SqlDataAdapter 充当 DataSet 和 SQL Server 之间的桥梁,用于检索和保存数据。

在您描述的场景中,不需要“桥梁”。您只需使用 a SqlCommand,将集合添加SqlParameter到其中,然后调用ExecuteNonQuery()以执行插入。

using(SqlConnection connection = new SqlConnection(@"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2"))
{
    using(SqlCommand command = new SqlCommand(sql, connection))
    {
        try
        {
            connection.Open();  
            for (int i =0; i< gridView3.RowCount; i++)
            {
                SqlParameter parameter = new SqlParameter();
                // TODO: handle name accordingly (MName, LName etc.)
                parameter.ParameterName = "@FName";
                // TODO: handle type accordingly
                parameter.SqlDbType = SqlDbType.NVarChar; 
                parameter.Direction = ParameterDirection.Input;
                // TODO: use the field name accordingly
                parameter.Value = Convert.ToString(gridView3.GetRowCellValue(i, "FieldName"));
                // add the parameter to the command
                command.Parameters.Add(parameter);
            }
            command.ExecuteNonQuery();
        }
        catch(Exception)
        {
            // TODO: handle the exception
        }

    }
}

备注:您应该在代码中处理与 SQL 相关的对象 - 一种方便的方法是使用using语句。

于 2013-02-06T11:43:46.407 回答