使用adapter.update()从datatable更新SQL时出错

时间:2014-12-08 00:29:52

标签: c# datagridview datatable type-conversion sqlcommand

根据目前为止的答案,我似乎没有正确创建参数而没有正确传递值。我想从DataTable更新SQL表(数据表是从SQL表填充的,列名是相同的)当我创建参数时,我认为第二个参数代表了数据表列。如何设置数据表" DWFieldScale"的值。被传递给SQL列DWFieldScale ??? (对于我创建的每个其他参数都相同)

command.Parameters.AddWithValue(" @ DWFieldScale"," DWFieldScale");

我在调用adapter.update()时遇到SQL异常,因为我不了解如何在主题标题中正确设置适配器。我几个月才和C#一起工作,所以我还很绿。

无论如何,我已经尝试了十几件事,并且已经达到了我可能会做到的地步'在正确的轨道上,但我得到了一个“无法将NVARCHAR转换为INT'困扰我的是这是一个绑定到数据表的DataGridView,其中列是INT类型。 (在SQL中,列可以为空,并且有空值)

  1. NVARCHAR来自哪里?
  2. 如果NVARCHAR来自DataGridView,为什么它不能使用匹配类型自动生成?
  3. 我在哪里可以进行转换以允许我的da.Update(tblvAttributes);指挥工作?我在定义参数时尝试了几件事,但一定不要紧紧抓住我的下巴。帮助
  4. 我的绑定代码:

    private void tvVX130_AfterSelect(object sender, TreeViewEventArgs e)
            {
                string t = tvVX130.SelectedNode.Text;
                BindingSource bs1 = new BindingSource();
                bs1.PositionChanged += bindingSource1_PositionChanged;
                bs1.DataSource = tblvAttributes;
                dgvVX130.DataSource = bs1;
                string dwTN = tvVX130.SelectedNode.Text.Substring(0, tvVX130.SelectedNode.Text.IndexOf("  -  "));
                bs1.Filter = "DWPhysicalTableName = '" + dwTN +  "' AND DWPhysicalSchemaName = '" + t.Substring(t.IndexOf("  -  ") + 5) + "'";
                dgvVX130.DataSource = bs1;
    
          public static SqlDataAdapter CreateSQLAdapter(SqlConnection vx130)
        {
            SqlDataAdapter da = new SqlDataAdapter();
    
           command = new SqlCommand(
                "UPDATE [Meta].[AttributeMap] "+
                "SET DatabaseName = @DatabaseName, DWPhysicalSchemaName = @DWPhysicalSchemaName, " +
                "DWPhysicalTableName=@DWPhysicalTableName, DWFieldName=@DWFieldName, DataDomain=@DataDomain," +
                "DWFieldDataType=@DWFieldDataType, DWFieldLength=@DWFieldLength, DWFieldScale=@DWFieldScale," +
                "SourceAttributeSID=@SourceAttributeSID  " +
    
                "WHERE DWPhysicalSchemaName = @DWPhysicalSchemaName and DWPhysicalTableName= @DWPhysicalTableName and DWFieldName=@DWFieldName", vx130);
    
            command.Parameters.AddWithValue("@DatabaseName", "DatabaseName");
            command.Parameters.AddWithValue("@DWPhysicalSchemaName", "DWPhysicalSchemaName");
            command.Parameters.AddWithValue("@DWPhysicalTableName", "DWPhysicalTableName");
            command.Parameters.AddWithValue("@DWFieldName", "DWFieldName");
            command.Parameters.AddWithValue("@DWFieldDataType", "DWFieldDataType");
            command.Parameters.AddWithValue("@DWFieldLength", "DWFieldLength");
            //command.Parameters.AddWithValue("@DWFieldScale",  "DWFieldScale");  gives can't convert NVARCHAR to INT
    
            //if (!String.IsNullOrWhiteSpace("DWFieldScale"))       Doesn't recognize "DWFieldScale" as column
            //    command.Parameters.AddWithValue("@DWFieldScale", "DWFieldScale");
            //else
            //    command.Parameters.AddWithValue("@DWFieldScale", DBNull.Value);
    
            //command.Parameters.Add("@DWFieldScale", SqlDbType.Int);
            //command.Parameters["@DWFieldScale"].Value = "DWFieldScale";  Doesn't recognize "DWFieldScale" as column
    
            //command.Parameters.AddWithValue("@DWFieldScale", int.Parse("DWFieldScale".ToString()));   gives input incorrect format
    
            command.Parameters.AddWithValue("@SourceAttributeSID",  "SourceAttributeSID");  //this is also integer
    
            da.UpdateCommand = command;
    

4 个答案:

答案 0 :(得分:1)

如果数据库字段是" int":

,则以下行会出错
command.Parameters.AddWithValue("@DWFieldScale", "DWFieldScale"); 

它会产生错误,因为您将字符串传递给字段" DWFieldScale"。 command.Parameters背后的想法是让你需要进行任何转换的控件。

见:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx

NVARCHAR是连接认为您尝试传递给参数的类型。它是一个数据库字段类型。

此外,以下行很奇怪:

if (!String.IsNullOrWhiteSpace("DWFieldScale"))

String.IsNullOrWhiteSpace旨在与"变量"一起使用。您正在传递一个常量字符串。函数的结果将始终为true,因为THERE是一个字符串,if的结果将始终为FALSE,因为您否定了函数的结果。

最后,这两行在开始时会因同样的原因失败,你设置一个int参数,但是传递一个字符串作为值:

command.Parameters.Add("@DWFieldScale", SqlDbType.Int);
command.Parameters["@DWFieldScale"].Value = "DWFieldScale";

使用参数的正确方法更像是:

command.Parameters.Add("@DWFieldScale", SqlDbType.Int);
command.Parameters["@DWFieldScale"].Value = 10;

所以,你必须传递一个VALUE,可以是一个常量,一个具有相同类型的变量,一个具有相同类型的函数的结果,等等。但实际上,必须是你想要在sql中的valyue命令。

但是这是你想要执行命令的时候。 如果要将其绑定到数据网格或类型的某些内容,只需添加参数即可。不传递值,因为更新数据网格时将设置值。

所以,只需使用这样的行:

command.Parameters.Add("@DWFieldScale", SqlDbType.Int);

让视图为你处理价值观。

这里有一个很好的例子,说明如何使用DAtaSet(在内存中)

http://msdn.microsoft.com/en-us/library/system.data.dataset%28v=vs.110%29.aspx

示例适用于" Select"声明,但你会得到这个想法:)

这里有一些关于SQLDataAdapter的信息: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter%28v=vs.110%29.aspx

答案 1 :(得分:1)

对于下一个程序员开始,这是我在编辑绑定到DataTable的DataGridView时自动更新SQL数据库/表的完整解决方案:

绑定:(将dgView,dTable和& PositionChange事件联系在一起)

private void tvVX130_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string t = tvVX130.SelectedNode.Text;
            BindingSource bs1 = new BindingSource();
            bs1.PositionChanged += bindingSource1_PositionChanged;
            bs1.DataSource = tblvAttributes;
            dgvVX130.DataSource = bs1;
            string dwTN = tvVX130.SelectedNode.Text.Substring(0, tvVX130.SelectedNode.Text.IndexOf("  -  "));
            bs1.Filter = "DWPhysicalTableName = '" + dwTN +  "' AND DWPhysicalSchemaName = '" + t.Substring(t.IndexOf("  -  ") + 5) + "'";
            dgvVX130.DataSource = bs1;
        }

创建执行适配器更新的事件:         private void bindingSource1_PositionChanged(object sender,EventArgs e)         {             var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);             AppSettingsSection appSettingSection =(AppSettingsSection)config.GetSection(“cbSettings”);             SqlConnection vx130 = new SqlConnection(appSettingSection.Settings [cbRegion.SelectedItem.ToString()]。Value);             SqlDataAdapter da = CreateSQLAdapter(vx130);             da.Update(tblvAttributes);         }

设置SQL适配器:(所有好东西都在。它也很冗长。另一种方法是重新调用语句来调用SQL存储过程。我没有。)

public static SqlDataAdapter CreateSQLAdapter(SqlConnection vx130)
        {
            SqlDataAdapter da = new SqlDataAdapter();

            // Create the SelectCommand.
            SqlCommand command = new SqlCommand("Select DatabaseName, DWPhysicalSchemaName, DWPhysicalTableName, " + 
                "DWFieldName ,DataDomain, DWFieldDataType, DWFieldLength, DWFieldScale, SourceAttributeSID, "+
                "ResolvedValue, PointedToField, MapComments, PrimaryKeyEntitySID, SpecialHandlingFlag, "+
                "DWFieldTechnicalDescription, BuildStatus from meta.attributemap", vx130);

            da.SelectCommand = command;

            // Create the InsertCommand.
            command = new SqlCommand(
             "Insert Into [Meta].[AttributeMap] " +
                "(DatabaseName, DWPhysicalSchemaName, DWPhysicalTableName, " +
                "DWFieldName ,DataDomain, DWFieldDataType, DWFieldLength, DWFieldScale, SourceAttributeSID, " +
                "ResolvedValue, PointedToField, MapComments, PrimaryKeyEntitySID, SpecialHandlingFlag, " +
                "DWFieldTechnicalDescription, BuildStatus ) " +


             "Values (@DatabaseName, @DWPhysicalSchemaName, @DWPhysicalTableName, " +
                "@DWFieldName ,@DataDomain, @DWFieldDataType, @DWFieldLength, @DWFieldScale, @SourceAttributeSID, " +
                "@ResolvedValue, @PointedToField, @MapComments, @PrimaryKeyEntitySID, @SpecialHandlingFlag, " +
                "@DWFieldTechnicalDescription, @BuildStatus)" , vx130);

            // Add the parameters for the InsertCommand.
            command.Parameters.Add(new SqlParameter("@DatabaseName", SqlDbType.VarChar));
            command.Parameters["@DatabaseName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DatabaseName"].SourceColumn = "DatabaseName";

            command.Parameters.Add(new SqlParameter("@DWPhysicalSchemaName", SqlDbType.VarChar));
            command.Parameters["@DWPhysicalSchemaName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWPhysicalSchemaName"].SourceColumn = "DWPhysicalSchemaName";

            command.Parameters.Add(new SqlParameter("@DWPhysicalTableName", SqlDbType.VarChar));
            command.Parameters["@DWPhysicalTableName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWPhysicalTableName"].SourceColumn = "DWPhysicalTableName";

            command.Parameters.Add(new SqlParameter("@DWFieldName", SqlDbType.VarChar));
            command.Parameters["@DWFieldName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldName"].SourceColumn = "DWFieldName";

            command.Parameters.Add(new SqlParameter("@DataDomain", SqlDbType.VarChar));
            command.Parameters["@DataDomain"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DataDomain"].SourceColumn = "DataDomain";

            command.Parameters.Add(new SqlParameter("@DWFieldDataType", SqlDbType.VarChar));
            command.Parameters["@DWFieldDataType"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldDataType"].SourceColumn = "DWFieldDataType";

            command.Parameters.Add(new SqlParameter("@DWFieldLength", SqlDbType.VarChar));
            command.Parameters["@DWFieldLength"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldLength"].SourceColumn = "DWFieldLength";

            command.Parameters.Add(new SqlParameter("@DWFieldScale", SqlDbType.Int));
            command.Parameters["@DWFieldScale"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldScale"].SourceColumn = "DWFieldScale";

            command.Parameters.Add(new SqlParameter("@SourceAttributeSID", SqlDbType.Int));
            command.Parameters["@SourceAttributeSID"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@SourceAttributeSID"].SourceColumn = "SourceAttributeSID";

            command.Parameters.Add(new SqlParameter("@ResolvedValue", SqlDbType.VarChar));
            command.Parameters["@ResolvedValue"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@ResolvedValue"].SourceColumn = "ResolvedValue";

            command.Parameters.Add(new SqlParameter("@PointedToField", SqlDbType.VarChar));
            command.Parameters["@PointedToField"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@PointedToField"].SourceColumn = "PointedToField";

            command.Parameters.Add(new SqlParameter("@MapComments", SqlDbType.VarChar));
            command.Parameters["@MapComments"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@MapComments"].SourceColumn = "MapComments";

            command.Parameters.Add(new SqlParameter("@PrimaryKeyEntitySID", SqlDbType.Int));
            command.Parameters["@PrimaryKeyEntitySID"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@PrimaryKeyEntitySID"].SourceColumn = "PrimaryKeyEntitySID";

            command.Parameters.Add(new SqlParameter("@SpecialHandlingFlag", SqlDbType.VarChar));
            command.Parameters["@SpecialHandlingFlag"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@SpecialHandlingFlag"].SourceColumn = "SpecialHandlingFlag";

            command.Parameters.Add(new SqlParameter("@DWFieldTechnicalDescription", SqlDbType.VarChar));
            command.Parameters["@DWFieldTechnicalDescription"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldTechnicalDescription"].SourceColumn = "DWFieldTechnicalDescription";

            command.Parameters.Add(new SqlParameter("@BuildStatus", SqlDbType.VarChar));
            command.Parameters["@BuildStatus"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@BuildStatus"].SourceColumn = "BuildStatus";

            da.InsertCommand = command;

            // Create the UpdateCommand.
            command = new SqlCommand(
                "UPDATE [Meta].[AttributeMap] "+
                "SET DatabaseName = @DatabaseName, DWPhysicalSchemaName = @DWPhysicalSchemaName, " +
                "DWPhysicalTableName=@DWPhysicalTableName, DWFieldName=@DWFieldName, DataDomain=@DataDomain," +
                "DWFieldDataType=@DWFieldDataType, DWFieldLength=@DWFieldLength, DWFieldScale=@DWFieldScale," +
                "SourceAttributeSID=@SourceAttributeSID, ResolvedValue=@ResolvedValue, @PointedToField=@PointedToField," +
                "MapComments=@MapComments, PrimaryKeyEntitySID=@PrimaryKeyEntitySID, SpecialHandlingFlag=@SpecialHandlingFlag," +
                "DWFieldTechnicalDescription=@DWFieldTechnicalDescription, BuildStatus=@BuildStatus  " +

                "WHERE DWPhysicalSchemaName = @DWPhysicalSchemaName and DWPhysicalTableName= @DWPhysicalTableName and DWFieldName=@DWFieldName", vx130);

            command.Parameters.Add(new SqlParameter("@DatabaseName", SqlDbType.VarChar));
            command.Parameters["@DatabaseName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DatabaseName"].SourceColumn = "DatabaseName";

            command.Parameters.Add(new SqlParameter("@DWPhysicalSchemaName", SqlDbType.VarChar));
            command.Parameters["@DWPhysicalSchemaName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWPhysicalSchemaName"].SourceColumn = "DWPhysicalSchemaName";

            command.Parameters.Add(new SqlParameter("@DWPhysicalTableName", SqlDbType.VarChar));
            command.Parameters["@DWPhysicalTableName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWPhysicalTableName"].SourceColumn = "DWPhysicalTableName";

            command.Parameters.Add(new SqlParameter("@DWFieldName", SqlDbType.VarChar));
            command.Parameters["@DWFieldName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldName"].SourceColumn = "DWFieldName";

            command.Parameters.Add(new SqlParameter("@DataDomain", SqlDbType.VarChar));
            command.Parameters["@DataDomain"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DataDomain"].SourceColumn = "DataDomain";

            command.Parameters.Add(new SqlParameter("@DWFieldDataType", SqlDbType.VarChar));
            command.Parameters["@DWFieldDataType"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldDataType"].SourceColumn = "DWFieldDataType";

            command.Parameters.Add(new SqlParameter("@DWFieldLength", SqlDbType.VarChar));
            command.Parameters["@DWFieldLength"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldLength"].SourceColumn = "DWFieldLength";

            command.Parameters.Add(new SqlParameter("@DWFieldScale", SqlDbType.Int));
            command.Parameters["@DWFieldScale"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldScale"].SourceColumn = "DWFieldScale";

            command.Parameters.Add(new SqlParameter("@SourceAttributeSID", SqlDbType.Int));
            command.Parameters["@SourceAttributeSID"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@SourceAttributeSID"].SourceColumn = "SourceAttributeSID";

            command.Parameters.Add(new SqlParameter("@ResolvedValue", SqlDbType.VarChar));
            command.Parameters["@ResolvedValue"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@ResolvedValue"].SourceColumn = "ResolvedValue";

            command.Parameters.Add(new SqlParameter("@PointedToField", SqlDbType.VarChar));
            command.Parameters["@PointedToField"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@PointedToField"].SourceColumn = "PointedToField";

            command.Parameters.Add(new SqlParameter("@MapComments", SqlDbType.VarChar));
            command.Parameters["@MapComments"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@MapComments"].SourceColumn = "MapComments";

            command.Parameters.Add(new SqlParameter("@PrimaryKeyEntitySID", SqlDbType.Int));
            command.Parameters["@PrimaryKeyEntitySID"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@PrimaryKeyEntitySID"].SourceColumn = "PrimaryKeyEntitySID";

            command.Parameters.Add(new SqlParameter("@SpecialHandlingFlag", SqlDbType.VarChar));
            command.Parameters["@SpecialHandlingFlag"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@SpecialHandlingFlag"].SourceColumn = "SpecialHandlingFlag";

            command.Parameters.Add(new SqlParameter("@DWFieldTechnicalDescription", SqlDbType.VarChar));
            command.Parameters["@DWFieldTechnicalDescription"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldTechnicalDescription"].SourceColumn = "DWFieldTechnicalDescription";

            command.Parameters.Add(new SqlParameter("@BuildStatus", SqlDbType.VarChar));
            command.Parameters["@BuildStatus"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@BuildStatus"].SourceColumn = "BuildStatus";

            da.UpdateCommand = command;

            // Create the DeleteCommand.
            command = new SqlCommand(
                 "delete from vx130.Meta.AttributeMap " +
                    " where DWPhysicalSchemaName =   @DWPhysicalSchemaName  AND " +
                       " DWPhysicalTableName =  @DWPhysicalTableName  AND  DWFieldName = @DWFieldName", vx130);

            // Add the parameters for the DeleteCommand.
            command.Parameters.Add(new SqlParameter("@DWPhysicalSchemaName", SqlDbType.VarChar));
            command.Parameters["@DWPhysicalSchemaName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWPhysicalSchemaName"].SourceColumn = "DWPhysicalSchemaName";

            command.Parameters.Add(new SqlParameter("@DWPhysicalTableName", SqlDbType.VarChar));
            command.Parameters["@DWPhysicalTableName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWPhysicalTableName"].SourceColumn = "DWPhysicalTableName";

            command.Parameters.Add(new SqlParameter("@DWFieldName", SqlDbType.VarChar));
            command.Parameters["@DWFieldName"].SourceVersion = DataRowVersion.Current;
            command.Parameters["@DWFieldName"].SourceColumn = "DWFieldName";

            da.DeleteCommand = command;

            return da;
        }
    }

}

答案 2 :(得分:0)

代码中的两行我认为您将字符串值分配给 int 参数我的意思是:

command.Parameters.AddWithValue("@DWFieldLength", "DWFieldLength");
command.Parameters.AddWithValue("@SourceAttributeSID",  "SourceAttributeSID"); 

尝试将参数值更改为 int ,还需要更改命令文本并将varchar参数放在单个qoto标记内;但是对于这种类型的数据库操作,最好使用存储过程而不是使用纯文本

答案 3 :(得分:0)

我认为问题是因为你在参数collection.in你的代码中添加了错误的值,所有列,你添加了字符串值。也许有些列是int类型

command.Parameters.AddWithValue("@DatabaseName", "DatabaseName");
    command.Parameters.AddWithValue("@DWPhysicalSchemaName", "DWPhysicalSchemaName");
    command.Parameters.AddWithValue("@DWPhysicalTableName", "DWPhysicalTableName");
    command.Parameters.AddWithValue("@DWFieldName", "DWFieldName");
    command.Parameters.AddWithValue("@DWFieldDataType", "DWFieldDataType");
    command.Parameters.AddWithValue("@DWFieldLength", "DWFieldLength");