0

これをパラメータ化するにはどうすればよいですか?!

string query = "";

            query += " SELECT DistID FROM Distributor";
            query += " WHERE Username = '" + username_id.Text + "'";
            query += " AND Password = '" + password.Text + "'";

            GeneralFunctions.GetData( query );

ここで実行できますか、それともGetDataメソッド内で実行する必要がありますか?

2つの方法は次のとおりです。

public static DataTable GetData ( string query )
{
    SqlDataAdapter dataAdapter;
    DataTable table;

    try
    {
        dataAdapter = new SqlDataAdapter( query, GetConnectionString() );
        table = new DataTable();

        dataAdapter.Fill( table );
        return table;
    }
    catch ( Exception ex )
    {
    }
    finally
    {
        dataAdapter = null;
        table = null;
    }

    return table;
}

public static string GetConnectionString ()
{
    string connectionString = ConfigurationManager.ConnectionStrings[ "CAPortalConnectionString" ].ConnectionString;

    return connectionString;
}
4

2 に答える 2

3

次のように、データベースをクエリするための特定のメソッドを設計することをお勧めします。

public static int? GetDistID(string username, string password)
{
    using (var conn = new SqlConnection(GetConnectionString()))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = 
        @"SELECT 
              DistID 
          FROM 
              Distributor
          WHERE 
              Username = @username 
          AND 
              Password = @password";
        cmd.Parameters.AddWithValue("@username", username);
        cmd.Parameters.AddWithValue("@password", password);
        using (var reader = cmd.ExecuteReader())
        {
            if (!reader.Read())
            {
                // no results found
                return null;
            }
            return reader.GetInt32(reader.GetOrdinal("DistID"));
        }
    }
}

その後:

var distId = GeneralFunctions.GetDistID(username_id.Text, password.Text);

DataTables / Sets/Adaptersは必要ありません。強く型付けされたオブジェクトを操作します。

于 2012-04-13T15:51:50.960 に答える
1

オブジェクトを使用するSqlCommandと、次のようなパラメーター化されたクエリを作成できます。

public object GetDistID(string username, string password)
{
    using (var conn = new SqlConnection("..."))
    {
        using (var cmd = new SqlCommand("SELECT DistID FROM Distributor WHERE Username=@Username AND Password=@Password", conn))
        {
            cmd.Connection.Open();
            cmd.Parameters.AddWithValue("@Username", username);
            cmd.Parameters.AddWithValue("@Password", password);                
            return cmd.ExecuteScalar();
        }
    }
}

役に立つ場合は、次のクラスを使用できます。ストアドプロシージャ向けに調整されていますが、クエリを受け入れるメソッドを追加するのは簡単なはずです。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;

namespace NESCTC.Data
{  
    public class DataAccess : IDisposable
    {
        #region declarations

        private SqlCommand _cmd;
        private string _SqlConnString;

        #endregion

        #region constructors

        public DataAccess(string ConnectionString)
        {
            _cmd = new SqlCommand();
            _cmd.CommandTimeout = 240;
            _SqlConnString = ConnectionString;
        }

        #endregion

        #region IDisposable implementation

        ~DataAccess()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);            
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _cmd.Connection.Dispose();
                _cmd.Dispose();
            }
        }

        #endregion

        #region data retrieval methods

        public DataTable ExecReturnDataTable()
        {
            using (SqlConnection conn = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    PrepareCommandForExecution(conn);
                    using (SqlDataAdapter adap = new SqlDataAdapter(_cmd))
                    {
                        DataTable dt = new DataTable();
                        adap.Fill(dt);
                        return dt;
                    }
                }
                catch
                {
                    _cmd.Connection.Close();
                    throw;
                }
                finally
                {
                    _cmd.Connection.Close();
                }
            }
        }    

        public object ExecScalar()
        {
            using (SqlConnection conn = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    PrepareCommandForExecution(conn);
                    return _cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    _cmd.Connection.Close();
                    throw ex;
                }
                finally
                {
                    _cmd.Connection.Close();
                }
            }
        }                

        #endregion

        #region data insert and update methods

        public void ExecNonQuery()
        {
            using (SqlConnection conn = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    PrepareCommandForExecution(conn);
                    _cmd.ExecuteNonQuery();
                }
                catch
                {
                    _cmd.Connection.Close();
                    throw;
                }
                finally
                {
                    _cmd.Connection.Close();
                }
            }
        }

        #endregion

        #region helper methods

        public void AddParm(string ParameterName, SqlDbType ParameterType, object Value)
        { _cmd.Parameters.Add(ParameterName, ParameterType).Value = Value; }

        private SqlCommand PrepareCommandForExecution(SqlConnection conn)
        {
            try
            {
                _cmd.Connection = conn;
                _cmd.CommandType = CommandType.StoredProcedure;
                _cmd.CommandTimeout = this.CommandTimeout;
                _cmd.Connection.Open();

                return _cmd;
            }
            catch
            {
                _cmd.Connection.Close();
                throw;
            }
        }

        #endregion

        #region properties

        public int CommandTimeout
        {
            get { return _cmd.CommandTimeout; }
            set { _cmd.CommandTimeout = value; }
        }

        public string ProcedureName
        {
            get { return _cmd.CommandText; }
            set { _cmd.CommandText = value; }
        }

        public string ConnectionString
        {
            get { return _SqlConnString; }
            set { _SqlConnString = value; }
        }

        #endregion
    }
}

次のようなクラスを使用できます。

public object GetDistID(string username, string password)
{
    using (var data = new DataAccess("ConnectionString"))
    {
        data.ProcedureName = "GetDistID";
        data.AddParm("@Username", SqlDbType.VarChar, username);
        data.AddParm("@Password", SqlDbType.VarChar, password);
        return data.ExecScalar();
    }
}
于 2012-04-13T16:05:37.097 に答える