ExecuteScalar 的话会有个异常 System.Data.SqlClient.SqlException: Syntax error converting the varchar value '123' to a column of data type int.
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters); 注意它返回的是object ————————————————例子: [C#]private string lookUpSingleItem(string connectionString, int productID){ try { string productName; // Call ExecuteScalar static method of SqlHelper class that returns an Object. Then cast the return value to string. // We pass in database connection string, command type, stored procedure name and productID SqlParameter productName = (string)SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, "getProductName", new SqlParameter("@ProductID", productID)); // return product name as a string return productName; } catch( Exception ex ) { // Log exception details throw ex; }}
System.Data.SqlClient.SqlException: Syntax error converting the varchar value '123' to a column of data type int.
注意它返回的是object
————————————————例子:
[C#]private string lookUpSingleItem(string connectionString, int productID){ try { string productName; // Call ExecuteScalar static method of SqlHelper class that returns an Object. Then cast the return value to string. // We pass in database connection string, command type, stored procedure name and productID SqlParameter productName = (string)SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, "getProductName", new SqlParameter("@ProductID", productID)); // return product name as a string return productName; } catch( Exception ex ) { // Log exception details throw ex; }}
我忘了加(string),没注意到ExecuteScalar返回是object.