首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >参数化更新

参数化更新
EN

Stack Overflow用户
提问于 2013-02-03 01:13:31
回答 1查看 6.3K关注 0票数 3

我正在尝试更新访问文件(.accdb)中的记录。我正在尝试使用.net OleDbCommand和OleDbParameters。我还试图使用通用模型,并将所有命令和参数存储在System.Data.Common抽象等效项中,这样我就可以轻松地切换到Server (我确实计划这样做)

,下面是实际使用的命令

编辑2/2/2013-9:10 command.ExecuteNonQuery在名为ExecuteNonQuery()的方法中,connectionString和命令是在DataAccess类构造函数中定义的

代码语言:javascript
复制
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"/>

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

编辑2/2/2013-9:10函数DataAccess.NewParameter在第一个代码块中

代码语言:javascript
复制
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));

我已经将查询复制到access中,并将所有参数名称替换为传递的实际数据,这很好。我尝试将SQL文本中的所有参数替换为?性格没有效果。我试图将方括号[]中的所有表名和列名附在一起,但也没有任何效果。

  • ID是一个AutoNumber字段
  • 标题是文本字段。
  • 图片是文本字段。
  • 颜色是一个长整数域。

以下是直接从Visual监视窗口中的参数复制的一些示例数据:

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

该ID确实存在于数据库中,并在查询执行后保持不变。

编辑2/2/2013-9:10我不知道如何检查哪个数据库实际上正在被更新,我唯一能想到的是,使用相同的连接字符串和连接对象,我用相同的ExecuteNonquery方法做了一个insert语句,它在我正在查看的数据库中工作。update语句就像这样工作得很好(没有参数):

代码语言:javascript
复制
DALayer.ExecuteNonQuery("UPDATE TileTypes SET Title = '" + titleTextBox.Text + 
"', Color = " + colorButton.BackColor.ToArgb() + ", Picture = '" + 
imageLocation + "' WHERE ID = " + id);

编辑2/2/2013 - 9:41pm我使用everything.exe搜索我的计算机上的所有data.accdb文件,除了原始的data.accdb文件之外,我没有找到实际的.accdb文件,但是我确实找到了这些.lnk文件,我认为它们不可能改变这个过程,但我还是要提到它。

data.accdb.LNK

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-04 02:16:45

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

下面是我最初如何构造这种多数据库连接类型的一小部分内容。我已经删除了一堆,并没有实际测试这个剥离版本,但它应该是您运行的一个很好的基线。

前提是基线"MyConnection“几乎是抽象的,但是有一些属性和一些在任何子类定义下都存在的”公共“方法。由此,每个函数和参数类型都是基于“i”面的,而不是特定的。但是,每个派生程序都将创建自己的适当类型。这就消除了“大小写”的需要。希望这有助于您与您的数据访问层的开发。

代码语言:javascript
复制
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....

        }
    }
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14668473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档