public class AccessDBUtil
    {
        private static String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=goods.mdb";
   public static string ExecuteScalar(string sql, OleDbParameter[] parameters)
        {
            //Debug.WriteLine(sql);
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand(sql, connection);
                try
                {
                    connection.Open();
                    if (parameters != null) cmd.Parameters.AddRange(parameters);
                    OleDbDataReader reader = cmd.ExecuteReader();
                    reader.Read();
                        string value = reader["gamename"].ToString();
                        return value;
                    
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
    }
}
调用代码:string sqlCount = "select top 1 id,gamename,gamearea,amount,price,costs from goods_ad where gamename=? and gamearea =?";
                OleDbParameter[] parameters = new OleDbParameter[2];
                parameters[0] = new OleDbParameter("@gamename", OleDbType.VarChar, 10);
                parameters[0].Value = treeform.InputValue;
                parameters[1] = new OleDbParameter("@gamearea", OleDbType.VarChar, 10);
                parameters[1].Value = treeform.Inputarea;
                this.amount.Text = AccessDBUtil.ExecuteScalar(sqlCount,parameters);
为什么我的数据有这一条记录,他还出错,找不到数那,为什么那,那指点一下,谢谢那。

解决方案 »

  1.   

    string sqlCount = "select top 1 id,gamename,gamearea,amount,price,costs from goods_ad where gamename=? and gamearea =?"; 换成
    string sqlCount = "select top 1 id,gamename,gamearea,amount,price,costs from goods_ad where gamename='"+treeform.InputValue+"' and gamearea ='"+treeform.Inputarea+"'"; 
    下面的添加参数的几条语句就不要了,还有就是你的ExecuteScalar()这个方法不用自己写,又现成的。要添加参数的是存储过程,如果不是存储过程,你可以直接赋值就行了。
      

  2.   

    string sqlCount = "select top 1 gamename, id,gamearea,amount,price,costs from goods_ad where gamename='"+treeform.InputValue+"' and gamearea ='"+treeform.Inputarea+"'";
    using (OleDbConnection conn = new OleDbConnection(Connstr))
    {
        string s_result = string.Empty;
        conn.Open();
        OleDbCommand comm = new OleDbCommand(sqlCount ,conn);
        object result = comm.ExecuteScalar();
        if(result != null)
        {
           s_result = (string) result;
        }
        conn.Close();
        return s_result;
    }//另外试一试你的SQL再Access里能运行不?