這個問題以前總是遇到
ADO
Provider Named/Positional Parameter Marker
SqlClient Named @parmname
OracleClient Named parmname (or parmname)
OleDb Positional ?
Odbc Positional ?
在DbCommand
這種不統一使得要寫出跨越各種數據提供者的程序變得復雜了
下面是一段示例代碼
//create proc TestParam
//@courseid varchar(
//as
//select * from course where courseid=@courseid
using System;
using System
using System
using System
using System
using System
namespace ADOParameterTest
class Program
enum ConnectionType : byte
static string sqlConnectionString =
static string oleConnectionString =
static DbConnection GetConnection(ConnectionType ct)
if (ct == ConnectionType
return new SqlConnection(sqlConnectionString);
}
else
return new OleDbConnection(oleConnectionString);
}
}
static void TestOleCommandText()
Console
using(DbConnection con = GetConnection(ConnectionType
con
DbCommand cmd = con
//cmd
cmd
//odbc&oledb只能是?做占位符
DbParameter p = cmd
p
p
cmd
//下面被注釋的參數設置方式也是對的
//記住參數名是沒有意義的
//cmd
ShowResult(cmd
}
}
static void TestOleStoredProcedure()
Console
using (DbConnection con = GetConnection(ConnectionType
con
DbCommand cmd = con
cmd
cmd
Console
//odbc&oledb只能是?做占位符
DbParameter p = cmd
p
p
cmd
//下面被注釋的參數設置方式也是對的
//記住參數名是沒有意義的
//cmd
ShowResult(cmd
Console
p
ShowResult(cmd
}
}
static void TestSqlCommandText()
Console
using (DbConnection con = GetConnection(ConnectionType
con
DbCommand cmd = con
//sql只能是@param做占位符
//oracle只能用:param做占位符
cmd
DbParameter p = cmd
p
p
cmd
//下面被注釋的參數設置方式也是對的
//記住只有參數名有意義
//cmd
ShowResult(cmd
}
}
static void TestSqlStoredProcedure()
Console
using (DbConnection con = GetConnection(ConnectionType
con
DbCommand cmd = con
//sql只能是@param做占位符
//oracle只能用:param做占位符
cmd
cmd
Console
DbParameter p = cmd
p
p
cmd
//下面被注釋的參數設置方式也是對的
//記住只有參數名有意義
//cmd
ShowResult(cmd
Console
p
ShowResult(cmd
}
}
static void ShowResult(DbDataReader reader)
int count = reader
while(reader
Console
for(int i=
Console
}
}
reader
Console
}
static void Main(string[] args)
try
TestOleCommandText();
TestSqlCommandText();
TestOleStoredProcedure();
TestSqlStoredProcedure();
}
catch (Exception ex)
Console
}
Console
}
}
}
From:http://tw.wingwit.com/Article/program/net/201311/12944.html