参数化更新

时间:2013-02-03 01:13:32

标签: c# .net sql ms-access parameters

我正在尝试更新访问文件(.accdb)中的记录。我正在尝试使用.net OleDbCommand和OleDbParameters。我也尝试使用通用模型并将所有命令和参数存储在System.Data.Common抽象等价物中,以便我可以轻松切换到SQL Server(我打算这样做)

所以这是使用的实际命令

编辑2013年2月2日 - 晚上9:10 command.ExecuteNonQuery位于名为ExecuteNonQuery()的方法内 connectionString和command在DataAccess类构造函数

中定义
public class DataAccess
{

    private string connectionString;
    private DbConnection connection;
    private DbCommand command;
    private DbDataReader reader;
    private DataTable data;

    public DataAccess()
    {
        connectionString = ConfigurationSettings.AppSettings["ConnectionString"];

        switch (ConfigurationSettings.AppSettings["DataBaseType"])
        {
            case "oledb":
                connection = new OleDbConnection(connectionString);
                command = new OleDbCommand(string.Empty, (OleDbConnection)connection);
                break;
            case "SQL":                 
                connection = new SqlConnection(connectionString);
                command = new SqlCommand(string.Empty, (SqlConnection)connection);
                break;
            default:
                break;
        }

    }

    public void ExecuteNonQuery(string SQL, params DbParameter[] parameters)
    {
        command.CommandType = CommandType.Text;
        command.CommandText = SQL;
        command.Parameters.AddRange(parameters);

        try
        {
            command.Connection.Open();

            try
            {
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                command.Connection.Close();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public DbParameter NewParameter(string name, object value)
    {
        DbParameter param;

        switch (ConfigurationSettings.AppSettings["DataBaseType"])
        {
            case "oledb":
                param = new OleDbParameter(name, value);
                break;
            case "SQL":
                param = new SqlParameter(name, value);
                break;
            default:
                param = null;
                break;
        }

        return param;
    }

这些是App.Config文件中的属性

<add key="DataBaseType" value="oledb"/>

<add key="ConnectionString" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=data.accdb"/>

现在问题是在更新语句中使用参数时,更新永远不会发生,也永远不会抛出错误。这是它的代码。

编辑2013年2月2日 - 晚上9:10 函数DataAccess.NewParameter位于第一个代码块

DALayer.ExecuteNonQuery("UPDATE TileTypes SET Title = @Title, Picture = @Picture, Color = @Color WHERE ID = @ID",
 DALayer.NewParameter("@Title", titleTextBox.Text.Trim()),
 DALayer.NewParameter("@Picture", typePictureBox.ImageLocation),
 DALayer.NewParameter("@Color", colorButton.BackColor.ToArgb()),
 DALayer.NewParameter("@ID", id));

我已将查询复制到访问中,并将所有参数名称替换为传递的实际数据,这样可以正常工作。我试过将SQL文本中的所有参数替换为?性格无效。我已经尝试将括号[]中的所有表名和列名括起来也没有效果。

  • ID是自动编号字段
  • 标题是文本字段
  • 图片是文字字段
  • Color是Long Integer字段

这是直接从Visual Studio观察窗口中的参数复制的一些示例数据:

  • “编辑”(标题)
  • -1(颜色)
  • “data \ images \ Edit_000000.jpg”(图片)
  • 740(id)

该ID确实存在于数据库中,并且在执行查询后未更改。

编辑2013年2月2日 - 晚上9:10 我不确定如何检查哪个数据库实际上正在更新,我唯一能想到的是使用相同的连接字符串和连接对象我使用相同的ExecuteNonquery方法执行了一个insert语句,它在我正在查看的数据库中工作。并且update语句可以正常工作(没有参数):

DALayer.ExecuteNonQuery("UPDATE TileTypes SET Title = '" + titleTextBox.Text + 
"', Color = " + colorButton.BackColor.ToArgb() + ", Picture = '" + 
imageLocation + "' WHERE ID = " + id);

编辑2/2/2013 - 9:41 pm 我已经使用everything.exe在我的计算机上搜索我计算机上的所有data.accdb文件,我发现除了原始文件之外没有实际的.accdb文件,但我确实找到了这些.lnk文件,我不相信它们可能会有变化这个过程,但无论如何我都会提到它

data.accdb.LNK

1 个答案:

答案 0 :(得分:0)

您尝试做的事情是我过去也做过的事情,但允许连接到OleDB(例如Access,Visual FoxPro等),SQL-Server,SyBase SQLAnywhere,也许我的实现可能对您有帮助。首先,您将用于连接公共接口上的每个元素,例如IDbConnection,IDbCommand,IDbParameter等。

以下我发布的内容是我最初构建此类多数据库连接类型的一小部分。我已经删除了一堆并没有实际测试这个剥离版本,但它应该是你运行的良好基线。

前提是基线“MyConnection”几乎就像一个抽象,但具有属性和一些“常见”方法,这些方法将存在于EITHER子类定义下。由此,每个函数和参数类型都基于“I”接口,而不是特定的。但是,每个派生的都将创建其OWN正确类型。这消除了“案例”一切的需要。希望这可以帮助您进行数据访问层开发。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

// for OleDB (Access, VFP, etc)
using System.Data.OleDb;
// for SQL-Server
using System.Data.SqlClient;

namespace DataMgmt
{
    public class MyConnection
    {
        // no matter the connection to server, it will require some "handle"
        // that is of type "IDbConnection"
        protected IDbConnection sqlConnectionHandle;

        // when querying, ANY query could have an exception that needs to have
        // possible further review for handling
        public Exception LastException
        { get; protected set; }

        // When calling an execute command (select, insert, update, delete), 
        // they all can return how many rows affected
        public int RowsAffectedByQuery
        { get; protected set; }

        // different databases could have different connection strings. Make
        // virtual and throw exception so sub-classed must return proper formatted.
        public virtual string GetConnectionString()
        { throw new Exception("GetConnectionString() method must be overridden."); }

        // each has its own "IDbConnection" type too
        protected virtual IDbConnection SQLConnectionHandle()
        { return sqlConnectionHandle; }

        public virtual IDbCommand GetSQLDbCommand()
        { throw new Exception("GetSQLDbCommand() method must be overridden."); }

        // generic routine to get a data parameter...
        public virtual IDbDataParameter AddDbParmSpecificValue(string ParmName, object UnknownValue)
        { throw new Exception("AddDbParmSpecificValue() method must be overwritten per specific connection."); }

        // generic "Connection" since they are all based on IDbCommand...
        public override bool SQLConnect()
        {
            // pre-blank exception in case remnant from previous activity
            LastException = null;

            if (sqlConnectionHandle.State != System.Data.ConnectionState.Open)
                try
                {
                    // if not open, always make sure we get updated connection string
                    // if ever changed by some other "unknown" condition...
                    sqlConnectionHandle.ConnectionString = GetConnectionString();
                    sqlConnectionHandle.Open();
                }
                catch (Exception ex)
                {
                    // Preserve in generic sqlException" property for analysis OUTSIDE this function
                    LastException = ex;
                }

            // if NOT connected, display message to user and set error code and exception
            if (sqlConnectionHandle.State != System.Data.ConnectionState.Open)
                LastException = new Exception("Unable to open database connection.");

            // return if it IS successful at opening the connection (or was already open)
            return sqlConnectionHandle.State == System.Data.ConnectionState.Open;
        }

        // likewise disconnect could be common
        public void SQLDisconnect()
        {
            if (sqlConnectionHandle != null)
                if (sqlConnectionHandle.State == ConnectionState.Open)
                    sqlConnectionHandle.Close();
        }


        public bool SqlExecNonQuery( IDbCommand SQLCmd, DataTable oTbl)
        {
            // pre-clear exception
            LastException = null;

            // fill the table...
            SQLConnect();
            try
            {
                RowsAffectedByQuery = SQLCmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                LastException = e;
                throw e;
            }
            finally
            {
                SQLDisconnect();
            }

            // Its all ok if no exception error
            return LastException == null;
        }

    }


    // Now, build your connection manager per specific type
    public class MyAccessConnection : MyConnection
    {
        public MyAccessConnection()
        {   sqlConnectionHandle =  new OleDbConnection();   }

        public override string GetConnectionString()
        {   return "Your Connection String from AppSettings.. any changes if OleDb vs SQL"; }

        public override IDbCommand GetSQLDbCommand()
        {   return new OleDbCommand( "", (OleDbConnection)sqlConnectionHandle ); }

        public override IDbDataParameter AddDbParmSpecificValue(string ParmName, object UnknownValue)
        {   return new OleDbParameter( ParmName, UnknownValue );    }

    }

    public class MySQLConnection : MyConnection
    {
        public MySQLConnection()
        {   sqlConnectionHandle = new SqlConnection();  }

        public override string GetConnectionString()
        { return "Your Connection String from AppSettings... any alterations needed??? "; }

        public override IDbCommand GetSQLDbCommand()
        { return new SqlCommand ("", (SqlConnection)sqlConnectionHandle); }

        public override IDbDataParameter AddDbParmSpecificValue(string ParmName, object UnknownValue)
        { return new SqlParameter(ParmName, UnknownValue); }
    }



    // Now to implement... pick one... Access or SQL-Server for derivation...
    public class MyDataLayer : MyAccessConnection
    {
        public void SomeSQLCall()
        {
            IDbCommand sqlcmd = GetSQLDbCommand();
            sqlcmd.CommandText = "UPDATE TileTypes SET Title = @Title, "
                                + "Picture = @Picture, "
                                + "Color = @Color "
                                + "WHERE ID = @ID";
            sqlcmd.Parameters.Add( AddDbParmSpecificValue( "@Title", titleTextBox.Text.Trim() ));
            sqlcmd.Parameters.Add( AddDbParmSpecificValue( "@Picture", typePictureBox.ImageLocation) );
            sqlcmd.Parameters.Add( AddDbParmSpecificValue( "@Color", colorButton.BackColor.ToArgb()) );
            sqlcmd.Parameters.Add( AddDbParmSpecificValue(  "@ID", id));

        if( SqlExecNonQuery(sqlcmd))
            // Good to go
            DoSomethingWithTheData;
        else
            // Notify of whatever error thrown....

        }
    }
}

所以..正如你所看到的,我的最后一节特别是从EITHER Access OR SQL派生而来。然后,我可以创建我的方法来获取数据,调用更新,等等。获取一个SQL命令(返回正确的类型并自动附加到其对应的“连接句柄”对象,准备文本,添加参数,执行它。