如何添加参数

时间:2010-08-05 15:38:05

标签: .net oledb

如何添加参数我使用

我必须插入多值来制作子表格

string connectionString12 = ConfigurationManager.ConnectionStrings["mobile_db"].ConnectionString;
OleDbConnection con = new OleDbConnection(connectionString12);
OleDbCommand cmdinsert = new OleDbCommand("insert into brand_tbl (brand_name)values(@2GNetwork)", con);
Parameter ab = new Parameter();

2 个答案:

答案 0 :(得分:2)

对于每个参数,您需要创建一个参数对象,分配它的名称和值,并将参数添加到命令中。以下示例可以帮助您入门。

public void MyInsert(string twoGNetwork)
{
    string connectionString; // get your connection string here
    using (DbConnection connection = new OleDbConnection(connectionString))
    using (DbCommand command = connection.CreateCommand())
    {
        command.CommandText = "insert into brand_tbl (brand_name) values (@2GNetwork)";

        // Add parameters
        AddParameter(command, "@2GNetwork", twoGNetwork);

        connection.Open();
        command.ExecuteNonQuery();
    }
}

private static void AddParameter(DbCommand command, string name, object value)
{
    DbParameter param = command.CreateParameter();
    param.ParameterName = name;
    param.Value = value;
    command.Parameters.Add(param);
}

修改
我读到OLEDB可能会忽略参数的名称而只尊重订单。因此,请确保按照使用顺序添加参数。

答案 1 :(得分:-2)

我不确定我完全理解你的问题。除非您正在调用存储过程,否则不需要参数。如果要传入SQL查询,则可以传入string.Format()中的参数。

(以下示例为adapted from MSDN

string customerId = "NWIND"
string companyName = "Northwind Traders";

OleDbConnection myConnection = new OleDbConnection(myConnectionString);
string myInsertQuery = string.Format("INSERT INTO Customers (CustomerID, CompanyName) Values('{0}', '{1}')", customerId, companyName);
OleDbCommand myCommand = new OleDbCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();

但是,如果您希望调用存储过程,那么这就是使用OleDB的方法:

(以下示例为adapted from MSDN

OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand salesCMD = new OleDbCommand("SalesByCategory", nwindConn);
salesCMD.CommandType = CommandType.StoredProcedure;
OleDbParameter myParm = salesCMD.Parameters.Add("@CategoryName", OleDbType.VarChar, 15);
myParm.Value = "Beverages";
myConnection.Open();
OleDbDataReader myReader = salesCMD.ExecuteReader();
myConnection.Close();